Skip to content

Commit ed133ed

Browse files
committed
优化路由缓存的读取,admin启动时加载所有路由到redis,gateway-web启动时读取redis中缓存的路由进行初使化
1 parent 061ee61 commit ed133ed

File tree

8 files changed

+125
-80
lines changed

8 files changed

+125
-80
lines changed

gateway/gateway-admin/pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,12 @@
2323
<artifactId>jetcache-starter-redis</artifactId>
2424
<version>2.5.14</version>
2525
</dependency>
26+
<dependency>
27+
<groupId>org.springframework.cloud</groupId>
28+
<artifactId>spring-cloud-gateway-core</artifactId>
29+
<version>2.1.0.RELEASE</version>
30+
<scope>compile</scope>
31+
</dependency>
2632
</dependencies>
2733

2834
<build>

gateway/gateway-admin/src/main/java/com/springboot/cloud/gateway/admin/service/impl/GatewayRouteService.java

Lines changed: 40 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,27 @@
11
package com.springboot.cloud.gateway.admin.service.impl;
22

33
import com.alicp.jetcache.Cache;
4-
import com.alicp.jetcache.anno.CacheInvalidate;
54
import com.alicp.jetcache.anno.CacheType;
6-
import com.alicp.jetcache.anno.Cached;
75
import com.alicp.jetcache.anno.CreateCache;
86
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
97
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
8+
import com.fasterxml.jackson.core.type.TypeReference;
9+
import com.fasterxml.jackson.databind.ObjectMapper;
1010
import com.springboot.cloud.gateway.admin.dao.GatewayRouteMapper;
1111
import com.springboot.cloud.gateway.admin.entity.ov.GatewayRouteVo;
1212
import com.springboot.cloud.gateway.admin.entity.param.GatewayRouteQueryParam;
1313
import com.springboot.cloud.gateway.admin.entity.po.GatewayRoute;
1414
import com.springboot.cloud.gateway.admin.service.IGatewayRouteService;
1515
import lombok.extern.slf4j.Slf4j;
1616
import org.apache.commons.lang.StringUtils;
17+
import org.springframework.cloud.gateway.filter.FilterDefinition;
18+
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
19+
import org.springframework.cloud.gateway.route.RouteDefinition;
1720
import org.springframework.stereotype.Service;
1821

22+
import javax.annotation.PostConstruct;
23+
import java.io.IOException;
24+
import java.net.URI;
1925
import java.util.List;
2026
import java.util.stream.Collectors;
2127

@@ -25,34 +31,54 @@ public class GatewayRouteService extends ServiceImpl<GatewayRouteMapper, Gateway
2531

2632
private static final String GATEWAY_ROUTES = "gateway_routes::";
2733

28-
@CreateCache(cacheType = CacheType.REMOTE)
29-
private Cache<String, GatewayRouteVo> gatewayRouteCache;
34+
@CreateCache(name = GATEWAY_ROUTES, cacheType = CacheType.REMOTE)
35+
private Cache<String, RouteDefinition> gatewayRouteCache;
3036

3137
@Override
3238
public boolean add(GatewayRoute gatewayRoute) {
3339
boolean isSuccess = this.save(gatewayRoute);
34-
gatewayRouteCache.put(GATEWAY_ROUTES + gatewayRoute.getId(), new GatewayRouteVo(gatewayRoute));
40+
gatewayRouteCache.put(gatewayRoute.getRouteId(), gatewayRouteToRouteDefinition(gatewayRoute));
3541
return isSuccess;
3642
}
3743

3844
@Override
39-
@CacheInvalidate(name = GATEWAY_ROUTES, key = "#id")
4045
public boolean delete(String id) {
41-
boolean isSuccess = this.removeById(id);
42-
gatewayRouteCache.remove(GATEWAY_ROUTES + id);
43-
return isSuccess;
46+
GatewayRoute gatewayRoute = this.getById(id);
47+
gatewayRouteCache.remove(gatewayRoute.getRouteId());
48+
return this.removeById(id);
4449
}
4550

4651
@Override
47-
@CacheInvalidate(name = GATEWAY_ROUTES, key = "#gatewayRoute.id")
4852
public boolean update(GatewayRoute gatewayRoute) {
4953
boolean isSuccess = this.updateById(gatewayRoute);
50-
gatewayRouteCache.put(GATEWAY_ROUTES + gatewayRoute.getId(), new GatewayRouteVo(gatewayRoute));
54+
gatewayRouteCache.put(gatewayRoute.getRouteId(), gatewayRouteToRouteDefinition(gatewayRoute));
5155
return isSuccess;
5256
}
5357

58+
/**
59+
* 将数据库中json对象转换为网关需要的RouteDefinition对象
60+
*
61+
* @param gatewayRoute
62+
* @return RouteDefinition
63+
*/
64+
private RouteDefinition gatewayRouteToRouteDefinition(GatewayRoute gatewayRoute) {
65+
RouteDefinition routeDefinition = new RouteDefinition();
66+
routeDefinition.setId(gatewayRoute.getRouteId());
67+
routeDefinition.setOrder(gatewayRoute.getOrders());
68+
routeDefinition.setUri(URI.create(gatewayRoute.getUri()));
69+
ObjectMapper objectMapper = new ObjectMapper();
70+
try {
71+
routeDefinition.setFilters(objectMapper.readValue(gatewayRoute.getFilters(), new TypeReference<List<FilterDefinition>>() {
72+
}));
73+
routeDefinition.setPredicates(objectMapper.readValue(gatewayRoute.getPredicates(), new TypeReference<List<PredicateDefinition>>() {
74+
}));
75+
} catch (IOException e) {
76+
log.error("网关路由对象转换失败", e);
77+
}
78+
return routeDefinition;
79+
}
80+
5481
@Override
55-
@Cached(name = GATEWAY_ROUTES, key = "#id", cacheType = CacheType.REMOTE)
5682
public GatewayRoute get(String id) {
5783
return this.getById(id);
5884
}
@@ -65,10 +91,11 @@ public List<GatewayRouteVo> query(GatewayRouteQueryParam gatewayRouteQueryParam)
6591
}
6692

6793
@Override
94+
@PostConstruct
6895
public boolean overload() {
6996
List<GatewayRoute> gatewayRoutes = this.list(new QueryWrapper<>());
7097
gatewayRoutes.forEach(gatewayRoute ->
71-
gatewayRouteCache.put(GATEWAY_ROUTES + gatewayRoute.getId(), new GatewayRouteVo(gatewayRoute))
98+
gatewayRouteCache.put(gatewayRoute.getRouteId(), gatewayRouteToRouteDefinition(gatewayRoute))
7299
);
73100
log.info("全局初使化网关路由成功!");
74101
return true;

gateway/gateway-admin/src/main/resources/application.yml

Lines changed: 0 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -37,51 +37,10 @@ jetcache:
3737
default:
3838
type: caffeine
3939
keyConvertor: fastjson
40-
expireAfterWriteInMillis: 3600000
41-
expireAfterAccessInMillis: 1800000
42-
# 長時本地緩存,主要用于要求时效一般
43-
longTime:
44-
type: caffeine
45-
keyConvertor: fastjson
46-
expireAfterWriteInMillis: 300000
47-
expireAfterAccessInMillis: 180000
48-
# 短時本地緩存,主要用于要求时效较高的配置
49-
shortTime:
50-
type: caffeine
51-
keyConvertor: fastjson
52-
expireAfterWriteInMillis: 60000
53-
expireAfterAccessInMillis: 40000
5440
remote:
5541
# 默认2小时的远程缓存
5642
default:
5743
type: redis
58-
expireAfterWriteInMillis: 43200000
59-
keyConvertor: fastjson
60-
valueEncoder: kryo
61-
valueDecoder: kryo
62-
poolConfig:
63-
minIdle: 5
64-
maxIdle: 20
65-
maxTotal: 50
66-
host: ${REDIS_HOST:localhost}
67-
port: ${REDIS_PORT:6379}
68-
# 长时远程緩存,主要用于要求时效要求一般的集中式缓存
69-
longTime:
70-
type: redis
71-
expireAfterWriteInMillis: 7200000
72-
keyConvertor: fastjson
73-
valueEncoder: kryo
74-
valueDecoder: kryo
75-
poolConfig:
76-
minIdle: 5
77-
maxIdle: 20
78-
maxTotal: 50
79-
host: ${REDIS_HOST:localhost}
80-
port: ${REDIS_PORT:6379}
81-
# 短時远程緩存,主要用于要求时效较高的集中式缓存
82-
shortTime:
83-
type: redis
84-
expireAfterWriteInMillis: 300000
8544
keyConvertor: fastjson
8645
valueEncoder: kryo
8746
valueDecoder: kryo

gateway/gateway-web/pom.xml

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@
1818
</parent>
1919

2020
<dependencies>
21+
<!--core基础类库-->
22+
<dependency>
23+
<groupId>com.springboot.cloud</groupId>
24+
<artifactId>core</artifactId>
25+
<version>0.0.1-SNAPSHOT</version>
26+
</dependency>
2127
<!--api网关-->
2228
<dependency>
2329
<groupId>org.springframework.cloud</groupId>
@@ -39,16 +45,6 @@
3945
<artifactId>springfox-swagger2</artifactId>
4046
<version>2.9.2</version>
4147
</dependency>
42-
<dependency>
43-
<groupId>com.springboot.cloud</groupId>
44-
<artifactId>core</artifactId>
45-
<version>0.0.1-SNAPSHOT</version>
46-
</dependency>
47-
<dependency>
48-
<groupId>org.apache.commons</groupId>
49-
<artifactId>commons-pool2</artifactId>
50-
<version>2.6.0</version>
51-
</dependency>
5248
<!--网关签权客户端-->
5349
<dependency>
5450
<groupId>com.springboot.cloud</groupId>

gateway/gateway-web/src/main/java/com/springboot/cloud/gateway/GatewayApplication.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.springboot.cloud.gateway;
22

3+
import com.alicp.jetcache.anno.config.EnableCreateCacheAnnotation;
4+
import com.alicp.jetcache.anno.config.EnableMethodCache;
35
import org.springframework.boot.SpringApplication;
46
import org.springframework.boot.autoconfigure.SpringBootApplication;
57
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
@@ -10,6 +12,8 @@
1012
@EnableDiscoveryClient
1113
@EnableFeignClients(basePackages = "com.springboot.cloud.auth.client")
1214
@EnableCircuitBreaker
15+
@EnableMethodCache(basePackages = "com.springboot.cloud")
16+
@EnableCreateCacheAnnotation
1317
public class GatewayApplication {
1418
public static void main(String[] args) {
1519
SpringApplication.run(GatewayApplication.class, args);

gateway/gateway-web/src/main/java/com/springboot/cloud/gateway/service/impl/RouteService.java

Lines changed: 30 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,24 @@
11
package com.springboot.cloud.gateway.service.impl;
22

3-
import com.fasterxml.jackson.databind.ObjectMapper;
4-
import com.google.common.collect.Lists;
3+
import com.alicp.jetcache.Cache;
4+
import com.alicp.jetcache.anno.CacheType;
5+
import com.alicp.jetcache.anno.CreateCache;
56
import com.springboot.cloud.gateway.service.IRouteService;
67
import lombok.extern.slf4j.Slf4j;
8+
import org.apache.commons.lang3.StringUtils;
79
import org.springframework.beans.factory.annotation.Autowired;
810
import org.springframework.cloud.gateway.route.RouteDefinition;
911
import org.springframework.data.redis.core.StringRedisTemplate;
1012
import org.springframework.stereotype.Service;
1113
import org.springframework.util.CollectionUtils;
1214
import reactor.core.publisher.Mono;
1315

14-
import java.io.IOException;
15-
import java.util.*;
16+
import javax.annotation.PostConstruct;
17+
import java.util.Collection;
18+
import java.util.HashMap;
19+
import java.util.Map;
20+
import java.util.Set;
21+
import java.util.stream.Collectors;
1622

1723
@Service
1824
@Slf4j
@@ -23,36 +29,41 @@ public class RouteService implements IRouteService {
2329
@Autowired
2430
private StringRedisTemplate stringRedisTemplate;
2531

32+
@CreateCache(name = GATEWAY_ROUTES, cacheType = CacheType.REMOTE)
33+
private Cache<String, RouteDefinition> gatewayRouteCache;
34+
2635
private Map<String, RouteDefinition> routeDefinitionMaps = new HashMap<>();
2736

37+
@PostConstruct
2838
private void loadRouteDefinition() {
39+
log.info("loadRouteDefinition, 开始初使化路由");
2940
Set<String> gatewayKeys = stringRedisTemplate.keys(GATEWAY_ROUTES + "*");
30-
3141
if (CollectionUtils.isEmpty(gatewayKeys)) {
3242
return;
3343
}
34-
35-
List<String> gatewayRoutes = Optional.ofNullable(stringRedisTemplate.opsForValue().multiGet(gatewayKeys)).orElse(Lists.newArrayList());
36-
gatewayRoutes.forEach(value -> {
37-
try {
38-
RouteDefinition routeDefinition = new ObjectMapper().readValue(value, RouteDefinition.class);
39-
routeDefinitionMaps.put(routeDefinition.getId(), routeDefinition);
40-
} catch (IOException e) {
41-
log.error(e.getMessage());
42-
}
43-
});
44+
log.info("预计初使化路由, gatewayKeys:{}", gatewayKeys);
45+
// 去掉key的前缀
46+
Set<String> gatewayKeyIds = gatewayKeys.stream().map(key -> {
47+
return key.replace(GATEWAY_ROUTES, StringUtils.EMPTY);
48+
}).collect(Collectors.toSet());
49+
Map<String, RouteDefinition> allRoutes = gatewayRouteCache.getAll(gatewayKeyIds);
50+
log.info("gatewayKeys:{}", allRoutes);
51+
routeDefinitionMaps.putAll(allRoutes);
52+
log.info("共初使化路由信息:{}", routeDefinitionMaps.size());
4453
}
4554

4655
@Override
4756
public Collection<RouteDefinition> getRouteDefinitions() {
48-
loadRouteDefinition();
4957
return routeDefinitionMaps.values();
5058
}
5159

5260
@Override
5361
public Mono<Void> save(Mono<RouteDefinition> routeDefinitionMono) {
5462
return routeDefinitionMono.flatMap(routeDefinition -> {
5563
routeDefinitionMaps.put(routeDefinition.getId(), routeDefinition);
64+
gatewayRouteCache.put(routeDefinition.getId(), routeDefinition);
65+
log.info("新增路由1条:{}", routeDefinition);
66+
log.info("目前路由共{}条:", routeDefinitionMaps.size());
5667
return Mono.empty();
5768
});
5869
}
@@ -61,6 +72,9 @@ public Mono<Void> save(Mono<RouteDefinition> routeDefinitionMono) {
6172
public Mono<Void> delete(Mono<String> routeId) {
6273
return routeId.flatMap(id -> {
6374
routeDefinitionMaps.remove(id);
75+
gatewayRouteCache.remove(id);
76+
log.info("删除路由1条:{}", routeId);
77+
log.info("目前路由共{}条:", routeDefinitionMaps.size());
6478
return Mono.empty();
6579
});
6680
}

gateway/gateway-web/src/main/resources/application.yml

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ spring:
1111
lettuce:
1212
pool:
1313
max-active: 300
14+
datasource:
15+
driver-class-name: com.mysql.jdbc.Driver
16+
url: jdbc:${DATASOURCE_DBTYPE:mysql}://${DATASOURCE_HOST:localhost}:${DATASOURCE_PORT:3306}/sc_gateway?characterEncoding=UTF-8&useUnicode=true&useSSL=false
17+
username: ${DATASOURCE_USERNAME:root}
18+
password: ${DATASOURCE_PASSWORD:root123}
19+
1420
zipkin:
1521
enabled: true
1622
sender:
@@ -40,6 +46,29 @@ spring:
4046
rate-limiter: "#{@defaultRedisRateLimiter}" #SPEL表达式去的对应的bean
4147
key-resolver: "#{@apiKeyResolver}" #SPEL表达式去的对应的bean
4248

49+
jetcache:
50+
statIntervalMinutes: 15
51+
areaInCacheName: false
52+
hidePackages: com.springboot.cloud
53+
local:
54+
# 默认2小时本地缓存
55+
default:
56+
type: caffeine
57+
keyConvertor: fastjson
58+
remote:
59+
# 默认2小时的远程缓存
60+
default:
61+
type: redis
62+
keyConvertor: fastjson
63+
valueEncoder: kryo
64+
valueDecoder: kryo
65+
poolConfig:
66+
minIdle: 5
67+
maxIdle: 20
68+
maxTotal: 50
69+
host: ${REDIS_HOST:localhost}
70+
port: ${REDIS_PORT:6379}
71+
4372
#网关白名单,无需要签权url
4473
gate:
4574
ignore:

gateway/pom.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,15 @@
2727
<groupId>org.springframework.cloud</groupId>
2828
<artifactId>spring-cloud-starter-openfeign</artifactId>
2929
</dependency>
30+
<dependency>
31+
<groupId>com.alicp.jetcache</groupId>
32+
<artifactId>jetcache-starter-redis</artifactId>
33+
<version>2.5.14</version>
34+
</dependency>
35+
<dependency>
36+
<groupId>org.apache.commons</groupId>
37+
<artifactId>commons-pool2</artifactId>
38+
<version>2.6.0</version>
39+
</dependency>
3040
</dependencies>
3141
</project>

0 commit comments

Comments
 (0)