♻️ 重构代码。 动态路由部分抽取成公用组件

This commit is contained in:
冷冷 committed 2018-11-05 20:59:42 +08:00
1 parent d7b4cbfa60
commit e64d260712
12 files changed
+135 -9

No files matched your search

@@ -20,6 +20,7 @@
package com.pig4cloud.pigx.gateway;
import com.pig4cloud.pigx.common.gateway.annotation.EnablePigxDynamicRoute;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
@@ -28,6 +29,7 @@ import org.springframework.cloud.client.SpringCloudApplication;
* @date 2018年06月21日
* 网关应用
*/
@EnablePigxDynamicRoute
@SpringCloudApplication
public class PigxGatewayApplication {
@@ -1,73 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import cn.hutool.json.JSONObject;
import com.pig4cloud.pigx.common.core.util.R;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import java.util.Map;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* 动态路由业务端点
*/
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/route")
public class DynamicRouteEndpoint {
private final DynamicRouteHandler dynamicRouteHandler;
/**
* 获取当前定义的路由信息
*
* @return {"id":"RouteDefinition"}
*/
@GetMapping
public Mono<Map<String, RouteDefinition>> routes() {
return dynamicRouteHandler.routes();
}
/**
* 修改路由
*
* @param routes 路由定义
* @return
*/
@PutMapping
public R edit(@RequestBody JSONObject routes) {
return new R(dynamicRouteHandler.editRoutes(routes));
}
/**
* 回滚初始化配置
*
* @return
*/
@GetMapping("/fallback")
public Mono<R> fallback() {
return Mono.just(new R(dynamicRouteHandler.fallback()));
}
}
@@ -1,142 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.pig4cloud.pigx.common.core.constant.CommonConstant;
import com.pig4cloud.pigx.gateway.support.vo.RouteDefinitionVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.util.List;
import java.util.Map;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* 动态路由操作类
* see GatewayControllerEndpoint.java
*/
@Slf4j
@Service
public class DynamicRouteHandler implements ApplicationEventPublisherAware {
private final RouteDefinitionLocator routeDefinitionLocator;
private final RedisTemplate redisTemplate;
private ApplicationEventPublisher applicationEventPublisher;
public DynamicRouteHandler(RedisTemplate redisTemplate
, RouteDefinitionLocator routeDefinitionLocator) {
this.redisTemplate = redisTemplate;
this.routeDefinitionLocator = routeDefinitionLocator;
}
/**
* 获取全部路由
* <p>
* RedisRouteDefinitionWriter.java
* PropertiesRouteDefinitionLocator.java
*
* @return
*/
public Mono<Map<String, RouteDefinition>> routes() {
return routeDefinitionLocator.getRouteDefinitions()
.collectMap(RouteDefinition::getId);
}
/**
* 更新路由信息
*
* @param routes 路由信息
* @return
*/
public Mono<Void> editRoutes(JSONObject routes) {
Boolean result = redisTemplate.delete(CommonConstant.ROUTE_KEY);
log.info("清空网关路由 {} ", result);
routes.forEach((key, value) -> {
log.info("更新路由 -> {} ->{}", key, value);
RouteDefinitionVo vo = new RouteDefinitionVo();
Map<String, Object> map = (Map) value;
Object id = map.get("id");
if (id != null) {
vo.setId(String.valueOf(id));
}
Object predicates = map.get("predicates");
if (predicates != null) {
JSONArray predicatesArray = (JSONArray) predicates;
List<PredicateDefinition> predicateDefinitionList =
predicatesArray.toList(PredicateDefinition.class);
vo.setPredicates(predicateDefinitionList);
}
Object filters = map.get("filters");
if (filters != null) {
JSONArray filtersArray = (JSONArray) filters;
List<FilterDefinition> filterDefinitionList
= filtersArray.toList(FilterDefinition.class);
vo.setFilters(filterDefinitionList);
}
Object uri = map.get("uri");
if (uri != null) {
vo.setUri(URI.create(String.valueOf(uri)));
}
Object order = map.get("order");
if (order != null) {
vo.setOrder(Integer.parseInt(String.valueOf(order)));
}
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RouteDefinitionVo.class));
redisTemplate.opsForHash().put(CommonConstant.ROUTE_KEY, key, vo);
});
log.debug("更新网关路由结束 ");
this.applicationEventPublisher.publishEvent(new RefreshRoutesEvent(this));
return Mono.empty();
}
/**
* 回滚路由
*
* @return
*/
public Mono<Void> fallback() {
this.applicationEventPublisher.publishEvent(new DynamicRouteInitEvent(this));
return Mono.empty();
}
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
@@ -1,32 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import org.springframework.context.ApplicationEvent;
/**
* @author lengleng
* @date 2018/11/5
* <p>
* 路由初始化事件
*/
public class DynamicRouteInitEvent extends ApplicationEvent {
public DynamicRouteInitEvent(Object source) {
super(source);
}
}
@@ -1,75 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import com.pig4cloud.pigx.common.core.constant.CommonConstant;
import com.pig4cloud.pigx.gateway.support.vo.RouteDefinitionVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.cloud.gateway.config.PropertiesRouteDefinitionLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.scheduling.annotation.Async;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* 容器启动后保存配置文件里面的路由信息到Redis
*/
@Slf4j
@Configuration
@AllArgsConstructor
public class DynamicRouteInitRunner {
private final RedisTemplate redisTemplate;
private final GatewayProperties gatewayProperties;
@Async
@Order
@EventListener({WebServerInitializedEvent.class, DynamicRouteInitEvent.class})
public void initRoute() {
Boolean result = redisTemplate.delete(CommonConstant.ROUTE_KEY);
log.info("初始化网关路由 {} ", result);
gatewayProperties.getRoutes().forEach(route -> {
RouteDefinitionVo vo = new RouteDefinitionVo();
BeanUtils.copyProperties(route, vo);
log.info("加载路由ID:{},{}", route.getId(), vo);
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RouteDefinitionVo.class));
redisTemplate.opsForHash().put(CommonConstant.ROUTE_KEY, route.getId(), vo);
});
log.debug("初始化网关路由结束 ");
}
/**
* 配置文件设置为空redis 加载的为准
*
* @return
*/
@Bean
public PropertiesRouteDefinitionLocator propertiesRouteDefinitionLocator() {
return new PropertiesRouteDefinitionLocator(new GatewayProperties());
}
}
@@ -1,80 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support;
import com.pig4cloud.pigx.common.core.constant.CommonConstant;
import com.pig4cloud.pigx.gateway.support.vo.RouteDefinitionVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.ArrayList;
import java.util.List;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* redis 保存路由信息,优先级比配置文件高
*/
@Slf4j
@Component
@AllArgsConstructor
public class RedisRouteDefinitionWriter implements RouteDefinitionRepository {
private final RedisTemplate redisTemplate;
@Override
public Mono<Void> save(Mono<RouteDefinition> route) {
return route.flatMap(r -> {
RouteDefinitionVo vo = new RouteDefinitionVo();
BeanUtils.copyProperties(r, vo);
log.info("保存路由信息{}", vo);
redisTemplate.opsForHash().put(CommonConstant.ROUTE_KEY, r.getId(), vo);
return Mono.empty();
});
}
@Override
public Mono<Void> delete(Mono<String> routeId) {
routeId.subscribe(id -> {
log.info("删除路由信息{}", id);
redisTemplate.opsForHash().delete(CommonConstant.ROUTE_KEY, id);
});
return Mono.empty();
}
@Override
public Flux<RouteDefinition> getRouteDefinitions() {
List<RouteDefinitionVo> values = redisTemplate.opsForHash().values(CommonConstant.ROUTE_KEY);
List<RouteDefinition> definitionList = new ArrayList<>();
values.forEach(vo -> {
RouteDefinition routeDefinition = new RouteDefinition();
BeanUtils.copyProperties(vo, routeDefinition);
definitionList.add(vo);
});
log.debug("redis 中路由定义条数: {}, {}", definitionList.size(), definitionList);
return Flux.fromIterable(definitionList);
}
}
@@ -1,32 +0,0 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.gateway.support.vo;
import org.springframework.cloud.gateway.route.RouteDefinition;
import java.io.Serializable;
/**
* @author lengleng
* @date 2018/10/31
* <p>
* 扩展此类支持序列化a
* See RouteDefinition.class
*/
public class RouteDefinitionVo extends RouteDefinition implements Serializable {
}