SpringCloud Gateway使用redis實(shí)現(xiàn)動(dòng)態(tài)路由的方法
1. 將 actuator 端點(diǎn)暴露出來(lái)
management:
endpoints:
web:
exposure:
include: "*"
2. redis 配置
http://www.dhdzp.com/article/203766.htm
3. 將原內(nèi)存路由持久化到 redis
@Component
public class RedisRouteDefinitionRepository implements RouteDefinitionRepository {
/**
* hash存儲(chǔ)的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)));
});
}
}
4. 重寫(xiě)動(dòng)態(tài)路由服務(wù)
@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;
}
}
5. 對(duì)外暴露接口
@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);
}
}
測(cè)試
測(cè)試前刪除我們配置的靜態(tài)路由,因?yàn)殪o態(tài)路由和 redis 動(dòng)態(tài)路由同時(shí)存在時(shí)取并集。
訪問(wèn) http://localhost:2000/actuator/gateway/routes , 可以看到只有默認(rèn)路由。
[
{
"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
}
]
這個(gè)時(shí)候訪問(wèn) http://192.168.124.5:2000/idc-provider1/provider1/1 根據(jù)結(jié)果可以推測(cè)能正確路由到 provider1, 測(cè)試結(jié)果一致。
創(chuàng)建 provider1 路由,將路徑設(shè)置為 /p1/**,測(cè)試是否生效。
POST 請(qǐng)求 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
}
查看 redis 存儲(chǔ),或者請(qǐng)求 http://localhost:2000/actuator/gateway/routes , 都可以看到配置成功。
到此這篇關(guān)于SpringCloud Gateway使用redis實(shí)現(xiàn)動(dòng)態(tài)路由的文章就介紹到這了,更多相關(guān)SpringCloud Gateway動(dòng)態(tài)路由內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java虛擬機(jī)如何運(yùn)行Java字節(jié)碼
這篇文章主要介紹了Java虛擬機(jī)如何運(yùn)行Java字節(jié)碼的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
java使用CollectionUtils工具類(lèi)判斷集合是否為空方式
這篇文章主要介紹了java使用CollectionUtils工具類(lèi)判斷集合是否為空方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Spring boot + mybatis + orcale實(shí)現(xiàn)步驟實(shí)例代碼講解
這篇文章主要介紹了Spring boot + mybatis + orcale的實(shí)現(xiàn)步驟實(shí)例代碼講解,需要的朋友可以參考下2017-12-12
SpringBoot整合sharding-jdbc實(shí)現(xiàn)自定義分庫(kù)分表的實(shí)踐
本文主要介紹了SpringBoot整合sharding-jdbc實(shí)現(xiàn)自定義分庫(kù)分表的實(shí)踐,將通過(guò)自定義算法來(lái)實(shí)現(xiàn)定制化的分庫(kù)分表來(lái)擴(kuò)展相應(yīng)業(yè)務(wù),感興趣的可以了解一下2021-11-11
Spring?RestTemplate如何利用攔截器打印請(qǐng)求參數(shù)和返回狀態(tài)
這篇文章主要介紹了Spring?RestTemplate如何利用攔截器打印請(qǐng)求參數(shù)和返回狀態(tài)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
Java如何調(diào)用wsdl的webservice接口
這篇文章主要介紹了Java如何調(diào)用wsdl的webservice接口問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
Java 關(guān)鍵字static詳解及實(shí)例代碼
這篇文章主要介紹了Java 關(guān)鍵字static詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-04-04
原理分析SonarQube中IdentityProvider賬戶(hù)互斥現(xiàn)象
這篇文章主要為大家介紹分析SonarQube中IdentityProvider賬戶(hù)互斥現(xiàn)象原理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-02-02

