spring cloud gateway 动态路由实现:
- gateway-server(网关服务)
- dynamic-gateway(网关配置服务)
- redis
- mysql
- rabbitmq
配置服务:(这里的四个接口仅操作数据库)
image.png
配置服务修改数据后,调用“应用”接口,发送消息到队列,gateway-server消费消息,实现更新路由
image.png
配置服务实现启动时,加载数据库所有路由数据到redis,发送消息到队列,gateway-server实现消费
image.png
@Component
public class Receiver implements RouteDefinitionRepository {
private static final Logger log = LoggerFactory.getLogger(Receiver.class);
@Autowired
private RedisTemplate redisTemplate;
private String ROUTE_KEY = "gateway_route_key";
/**
* 此监听方法为路由修改使用(即增加,修改,删除路由后,点击“应用” 使用)
* @param str1
* @throws ClassNotFoundException
*/
@RabbitListener(queues = "topic.update")
public void update(String str1) throws ClassNotFoundException {
System.out.println(Thread.currentThread().getName()+"接收到来自topic.update队列的消息: "+str1);
Receiver.this.getRouteDefinitions();
log.info("更新路由成功!");
}
/**
* 配置服务启动时,发送消息到此队列
* @param str1
* @throws ClassNotFoundException
*/
@RabbitListener(queues = "topic.send")
public void send(String str1) throws ClassNotFoundException {
System.out.println(Thread.currentThread().getName()+"接收到来自topic.send队列的消息: "+str1);
Receiver.this.getRouteDefinitions();
log.info("初始化路由成功!");
}
@Override
public Flux<RouteDefinition> getRouteDefinitions() {
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RouteDefinition.class));
List<RouteDefinition> values = redisTemplate.opsForHash().values(ROUTE_KEY);
List<RouteDefinition> definitionList = new ArrayList<>();
values.forEach(vo ->{
RouteDefinition route = new RouteDefinition();
BeanUtils.copyProperties(vo,route);
definitionList.add(vo);
});
log.info("redis 中路由定义条数为:{},{}",definitionList.size(),definitionList);
return Flux.fromIterable(definitionList);
}
@Override
public Mono<Void> save(Mono<RouteDefinition> route) {
return route.flatMap(r -> {
RouteDefinition routeDefinition = new RouteDefinition();
BeanUtils.copyProperties(r,routeDefinition);
log.info("保存路由信息{}",routeDefinition);
redisTemplate.opsForHash().put(ROUTE_KEY,routeDefinition.getId(),routeDefinition);
return Mono.empty();
});
}
@Override
public Mono<Void> delete(Mono<String> routeId) {
routeId.subscribe(id -> {
log.info("删除路由的id为:{}",id);
redisTemplate.opsForHash().delete(ROUTE_KEY,id);
});
return Mono.empty();
}
}
源码+数据库:
qq:1782800572
网友评论