您好,登錄后才能下訂單哦!
怎么在SpringCloud Gateway中使用redis實現一個動態路由功能?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
management:
endpoints:
web:
exposure:
include: "*"
https://www.jb51.net/article/203766.htm
@Component public class RedisRouteDefinitionRepository implements RouteDefinitionRepository { /** * hash存儲的key */ public static final String GATEWAY_ROUTES = "gateway_dynamic_route"; @Resource private StringRedisTemplate redisTemplate; /** * 獲取路由信息 * @return */ @Override public Flux<RouteDefinition> getRouteDefinitions() { List<RouteDefinition> routeDefinitions = new ArrayList<>(); redisTemplate.opsForHash().values(GATEWAY_ROUTES).stream() .forEach(routeDefinition -> routeDefinitions.add(JSON.parseObject(routeDefinition.toString(), RouteDefinition.class))); return Flux.fromIterable(routeDefinitions); } @Override public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap(routeDefinition -> { redisTemplate.opsForHash().put(GATEWAY_ROUTES, routeDefinition.getId(), JSONObject.toJSONString(routeDefinition)); return Mono.empty(); }); } @Override public Mono<Void> delete(Mono<String> routeId) { return routeId.flatMap(id -> { if (redisTemplate.opsForHash().hasKey(GATEWAY_ROUTES, id)) { redisTemplate.opsForHash().delete(GATEWAY_ROUTES, id); return Mono.empty(); } return Mono.defer(() -> Mono.error(new NotFoundException("route definition is not found, routeId:" + routeId))); }); } }
@Service public class GatewayDynamicRouteService implements ApplicationEventPublisherAware { @Resource private RedisRouteDefinitionRepository redisRouteDefinitionRepository; private ApplicationEventPublisher applicationEventPublisher; /** * 增加路由 * @param routeDefinition * @return */ public int add(RouteDefinition routeDefinition) { redisRouteDefinitionRepository.save(Mono.just(routeDefinition)).subscribe(); applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); return 1; } /** * 更新 * @param routeDefinition * @return */ public int update(RouteDefinition routeDefinition) { redisRouteDefinitionRepository.delete(Mono.just(routeDefinition.getId())); redisRouteDefinitionRepository.save(Mono.just(routeDefinition)).subscribe(); applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this)); return 1; } /** * 刪除 * @param id * @return */ public Mono<ResponseEntity<Object>> delete(String id) { return redisRouteDefinitionRepository.delete(Mono.just(id)).then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build()))) .onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build())); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } }
@RestController @RequestMapping("/gateway") public class GatewayDynamicRouteController { @Resource private GatewayDynamicRouteService gatewayDynamicRouteService; @PostMapping("/add") public String create(@RequestBody RouteDefinition entity) { int result = gatewayDynamicRouteService.add(entity); return String.valueOf(result); } @PostMapping("/update") public String update(@RequestBody RouteDefinition entity) { int result = gatewayDynamicRouteService.update(entity); return String.valueOf(result); } @DeleteMapping("/delete/{id}") public Mono<ResponseEntity<Object>> delete(@PathVariable String id) { return gatewayDynamicRouteService.delete(id); } }
測試
測試前刪除我們配置的靜態路由,因為靜態路由和 redis 動態路由同時存在時取并集。
訪問 http://localhost:2000/actuator/gateway/routes , 可以看到只有默認路由。
[ { "route_id": "CompositeDiscoveryClient_consul", "route_definition": { "id": "CompositeDiscoveryClient_consul", "predicates": [ { "name": "Path", "args": { "pattern": "/consul/**" } } ], "filters": [ { "name": "RewritePath", "args": { "regexp": "/consul/(?<remaining>.*)", "replacement": "/${remaining}" } } ], "uri": "lb://consul", "order": 0 }, "order": 0 }, { "route_id": "CompositeDiscoveryClient_idc-gateway", "route_definition": { "id": "CompositeDiscoveryClient_idc-gateway", "predicates": [ { "name": "Path", "args": { "pattern": "/idc-gateway/**" } } ], "filters": [ { "name": "RewritePath", "args": { "regexp": "/idc-gateway/(?<remaining>.*)", "replacement": "/${remaining}" } } ], "uri": "lb://idc-gateway", "order": 0 }, "order": 0 }, { "route_id": "CompositeDiscoveryClient_idc-provider1", "route_definition": { "id": "CompositeDiscoveryClient_idc-provider1", "predicates": [ { "name": "Path", "args": { "pattern": "/idc-provider1/**" } } ], "filters": [ { "name": "RewritePath", "args": { "regexp": "/idc-provider1/(?<remaining>.*)", "replacement": "/${remaining}" } } ], "uri": "lb://idc-provider1", "order": 0 }, "order": 0 }, { "route_id": "CompositeDiscoveryClient_idc-provider2", "route_definition": { "id": "CompositeDiscoveryClient_idc-provider2", "predicates": [ { "name": "Path", "args": { "pattern": "/idc-provider2/**" } } ], "filters": [ { "name": "RewritePath", "args": { "regexp": "/idc-provider2/(?<remaining>.*)", "replacement": "/${remaining}" } } ], "uri": "lb://idc-provider2", "order": 0 }, "order": 0 } ]
這個時候訪問 http://192.168.124.5:2000/idc-provider1/provider1/1 根據結果可以推測能正確路由到 provider1, 測試結果一致。
創建 provider1 路由,將路徑設置為 /p1/**,測試是否生效。
POST 請求 http://localhost:2000/gateway/add
{ "id":"provider1", "predicates":[ { "name":"Path", "args":{ "_genkey_0":"/p1/**" } }, { "name":"RemoteAddr", "args":{ "_genkey_0":"192.168.124.5/16" } } ], "filters":[ { "name":"StripPrefix", "args":{ "_genkey_0":"1" } } ], "uri":"lb://idc-provider1", "order":0 }
看完上述內容,你們掌握怎么在SpringCloud Gateway中使用redis實現一個動態路由功能的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。