Browse Source

接口添加路由

yufeng0528 4 years ago
parent
commit
b759b54532

+ 3 - 0
.gitignore

@@ -3,3 +3,6 @@
3 3
 .classpath
4 4
 .project
5 5
 bin/
6
+*.iml
7
+spring5-admin/.idea/
8
+spring5-common/.idea/

+ 16 - 0
spring5-admin/pom.xml

@@ -16,6 +16,16 @@
16 16
     </parent>
17 17
 
18 18
 	<dependencies>
19
+	    <dependency>
20
+            <groupId>org.springframework.cloud</groupId>
21
+            <artifactId>spring-cloud-gateway-core</artifactId>
22
+        </dependency>
23
+        
24
+<!--         <dependency> -->
25
+<!--             <groupId>org.springframework.boot</groupId> -->
26
+<!--             <artifactId>spring-boot-starter-web</artifactId> -->
27
+<!--         </dependency> -->
28
+        
19 29
 		<!-- Spring Boot Redis 依赖 -->
20 30
 		<dependency>
21 31
 			<groupId>org.springframework.boot</groupId>
@@ -110,6 +120,12 @@
110 120
             <groupId>com.yaozhitech</groupId>
111 121
             <artifactId>spring5-auth-client</artifactId>
112 122
             <version>0.1.0</version>
123
+            <exclusions>
124
+                <exclusion>
125
+                    <groupId>org.springframework.boot</groupId>
126
+                    <artifactId>spring-boot-starter-webflux</artifactId>
127
+                </exclusion>
128
+            </exclusions>
113 129
         </dependency>
114 130
 
115 131
 	</dependencies>

+ 71 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/config/RedisConfig.java

@@ -0,0 +1,71 @@
1
+package com.yaozhitech.spring5.config;
2
+
3
+
4
+import org.springframework.cache.annotation.CachingConfigurerSupport;
5
+import org.springframework.context.annotation.Bean;
6
+import org.springframework.context.annotation.Configuration;
7
+import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
8
+import org.springframework.data.redis.connection.RedisConnectionFactory;
9
+import org.springframework.data.redis.core.ReactiveRedisTemplate;
10
+import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
11
+import org.springframework.data.redis.core.RedisTemplate;
12
+import org.springframework.data.redis.core.StringRedisTemplate;
13
+import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
14
+import org.springframework.data.redis.serializer.RedisSerializationContext;
15
+import org.springframework.data.redis.serializer.StringRedisSerializer;
16
+
17
+/**
18
+ * redis 配置
19
+ *
20
+ * @author yinzy
21
+ */
22
+@Configuration
23
+public class RedisConfig extends CachingConfigurerSupport {
24
+	
25
+	public static String cachePrefix = "bbc:";
26
+	
27
+    @Bean
28
+    public StringRedisSerializer stringRedisSerializer() {
29
+        return new StringRedisSerializer();
30
+    }
31
+
32
+    @Bean
33
+    public GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer() {
34
+        return new GenericJackson2JsonRedisSerializer();
35
+    }
36
+    
37
+    @Bean
38
+    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){
39
+        StringRedisTemplate template = new StringRedisTemplate();
40
+        template.setConnectionFactory(redisConnectionFactory);
41
+        return template;
42
+    }
43
+
44
+    @Bean
45
+    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,
46
+                                                       StringRedisSerializer stringRedisSerializer,
47
+                                                       GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer) {
48
+        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
49
+        redisTemplate.setConnectionFactory(redisConnectionFactory);
50
+        redisTemplate.setKeySerializer(stringRedisSerializer);
51
+        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
52
+        redisTemplate.setHashKeySerializer(stringRedisSerializer);
53
+        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
54
+        return redisTemplate;
55
+    }
56
+    
57
+    @Bean
58
+    public ReactiveRedisTemplate<Object, Object> reactiveRedisTemplate(ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
59
+    	ReactiveRedisTemplate<Object, Object> redisTemplate = new ReactiveRedisTemplate(reactiveRedisConnectionFactory, 
60
+    			RedisSerializationContext.fromSerializer(genericJackson2JsonRedisSerializer()));
61
+        return redisTemplate;
62
+    }
63
+    
64
+    
65
+    @Bean
66
+    public ReactiveStringRedisTemplate ReactiveStringRedisTemplate(ReactiveRedisConnectionFactory reactiveRedisConnectionFactory){
67
+    	ReactiveStringRedisTemplate template = new ReactiveStringRedisTemplate(reactiveRedisConnectionFactory);
68
+        return template;
69
+    }
70
+    
71
+}

+ 95 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/controller/GatewayRouteController.java

@@ -0,0 +1,95 @@
1
+package com.yaozhitech.spring5.controller;
2
+
3
+import javax.validation.Valid;
4
+
5
+import org.springframework.beans.factory.annotation.Autowired;
6
+import org.springframework.web.bind.annotation.PostMapping;
7
+import org.springframework.web.bind.annotation.RequestBody;
8
+import org.springframework.web.bind.annotation.RequestMapping;
9
+import org.springframework.web.bind.annotation.RestController;
10
+
11
+import com.yaozhitech.spring5.form.GatewayRoute;
12
+import com.yaozhitech.spring5.form.GatewayRouteForm;
13
+import com.yaozhitech.spring5.service.impl.GatewayRouteService;
14
+
15
+import io.swagger.annotations.Api;
16
+import io.swagger.annotations.ApiImplicitParam;
17
+import io.swagger.annotations.ApiOperation;
18
+import lombok.extern.slf4j.Slf4j;
19
+
20
+@RestController
21
+@RequestMapping("/gateway/routes")
22
+@Api("gateway routes")
23
+@Slf4j
24
+public class GatewayRouteController {
25
+
26
+    @Autowired
27
+    private GatewayRouteService gatewayRoutService;
28
+
29
+    @ApiOperation(value = "新增网关路由", notes = "新增一个网关路由")
30
+    @ApiImplicitParam(name = "gatewayRoutForm", value = "新增网关路由form表单", required = true, dataType = "GatewayRouteForm")
31
+    @PostMapping
32
+    public String add(@Valid @RequestBody GatewayRouteForm gatewayRoutForm) {
33
+        log.info("name:", gatewayRoutForm);
34
+        GatewayRoute gatewayRout = gatewayRoutForm.toPo(GatewayRoute.class);
35
+        gatewayRoutService.add(gatewayRout);
36
+        return "success";
37
+    }
38
+
39
+//    @ApiOperation(value = "删除网关路由", notes = "根据url的id来指定删除对象")
40
+//    @ApiImplicitParam(paramType = "path", name = "id", value = "网关路由ID", required = true, dataType = "long")
41
+//    @DeleteMapping(value = "/{id}")
42
+//    public Result delete(@PathVariable String id) {
43
+//        return Result.success(gatewayRoutService.delete(id));
44
+//    }
45
+//
46
+//    @ApiOperation(value = "修改网关路由", notes = "修改指定网关路由信息")
47
+//    @ApiImplicitParams({
48
+//            @ApiImplicitParam(name = "id", value = "网关路由ID", required = true, dataType = "long"),
49
+//            @ApiImplicitParam(name = "gatewayRoutForm", value = "网关路由实体", required = true, dataType = "GatewayRouteForm")
50
+//    })
51
+//    @PutMapping(value = "/{id}")
52
+//    public Result update(@PathVariable String id, @Valid @RequestBody GatewayRouteForm gatewayRoutForm) {
53
+//        GatewayRoute gatewayRout = gatewayRoutForm.toPo(GatewayRoute.class);
54
+//        gatewayRout.setId(id);
55
+//        return Result.success(gatewayRoutService.update(gatewayRout));
56
+//    }
57
+//
58
+//    @ApiOperation(value = "获取网关路由", notes = "根据id获取指定网关路由信息")
59
+//    @ApiImplicitParam(paramType = "path", name = "id", value = "网关路由ID", required = true, dataType = "long")
60
+//    @GetMapping(value = "/{id}")
61
+//    public Result get(@PathVariable String id) {
62
+//        log.info("get with id:{}", id);
63
+//        return Result.success(new GatewayRouteVo(gatewayRoutService.get(id)));
64
+//    }
65
+//
66
+//    @ApiOperation(value = "根据uri获取网关路由", notes = "根据uri获取网关路由信息,简单查询")
67
+//    @ApiImplicitParam(paramType = "query", name = "name", value = "网关路由路径", required = true, dataType = "string")
68
+//    @ApiResponses(
69
+//            @ApiResponse(code = 200, message = "处理成功", response = Result.class)
70
+//    )
71
+//    @GetMapping
72
+//    public Result getByUri(@RequestParam String uri) {
73
+//        return Result.success(gatewayRoutService.query(new GatewayRouteQueryParam(uri)).stream().findFirst());
74
+//    }
75
+//
76
+//    @ApiOperation(value = "搜索网关路由", notes = "根据条件查询网关路由信息")
77
+//    @ApiImplicitParam(name = "gatewayRoutQueryForm", value = "网关路由查询参数", required = true, dataType = "GatewayRouteQueryForm")
78
+//    @ApiResponses(
79
+//            @ApiResponse(code = 200, message = "处理成功", response = Result.class)
80
+//    )
81
+//    @PostMapping(value = "/conditions")
82
+//    public Result search(@Valid @RequestBody GatewayRouteQueryForm gatewayRouteQueryForm) {
83
+//        return Result.success(gatewayRoutService.query(gatewayRouteQueryForm.toParam(GatewayRouteQueryParam.class)));
84
+//    }
85
+//
86
+//    @ApiOperation(value = "重载网关路由", notes = "将所以网关的路由全部重载到redis中")
87
+//    @ApiResponses(
88
+//            @ApiResponse(code = 200, message = "处理成功", response = Result.class)
89
+//    )
90
+//    @PostMapping(value = "/overload")
91
+//    public Result overload() {
92
+//        return Result.success(gatewayRoutService.overload());
93
+//    }
94
+
95
+}

+ 34 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/form/BasePo.java

@@ -0,0 +1,34 @@
1
+package com.yaozhitech.spring5.form;
2
+
3
+import com.baomidou.mybatisplus.annotation.FieldFill;
4
+import com.baomidou.mybatisplus.annotation.IdType;
5
+import com.baomidou.mybatisplus.annotation.TableField;
6
+import com.baomidou.mybatisplus.annotation.TableId;
7
+import lombok.Data;
8
+
9
+import java.io.Serializable;
10
+import java.util.Date;
11
+
12
+@Data
13
+public class BasePo implements Serializable {
14
+
15
+	/**
16
+	 * 
17
+	 */
18
+	private static final long serialVersionUID = -191156952545501329L;
19
+
20
+	@TableId(type = IdType.ID_WORKER_STR)
21
+    private String id;
22
+
23
+    @TableField(fill = FieldFill.INSERT)
24
+    private String createdBy;
25
+
26
+    @TableField(fill = FieldFill.INSERT)
27
+    private Date createdTime;
28
+
29
+    @TableField(fill = FieldFill.INSERT_UPDATE)
30
+    private String updatedBy;
31
+
32
+    @TableField(fill = FieldFill.INSERT_UPDATE)
33
+    private Date updatedTime;
34
+}

+ 16 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/form/FilterDefinition.java

@@ -0,0 +1,16 @@
1
+package com.yaozhitech.spring5.form;
2
+
3
+import lombok.*;
4
+
5
+import java.util.LinkedHashMap;
6
+import java.util.Map;
7
+
8
+@EqualsAndHashCode
9
+@Data
10
+@Builder
11
+@NoArgsConstructor
12
+@AllArgsConstructor
13
+public class FilterDefinition {
14
+    private String name;
15
+    private Map<String, String> args = new LinkedHashMap<>();
16
+}

+ 22 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/form/GatewayRoute.java

@@ -0,0 +1,22 @@
1
+package com.yaozhitech.spring5.form;
2
+
3
+import lombok.AllArgsConstructor;
4
+import lombok.Builder;
5
+import lombok.Data;
6
+import lombok.EqualsAndHashCode;
7
+import lombok.NoArgsConstructor;
8
+
9
+@EqualsAndHashCode(callSuper = true)
10
+@Data
11
+@Builder
12
+@NoArgsConstructor
13
+@AllArgsConstructor
14
+public class GatewayRoute extends BasePo {
15
+    private String uri;
16
+    private String routeId;
17
+    private String predicates;
18
+    private String filters;
19
+    private String description;
20
+    private Integer orders = 0;
21
+    private String status = "Y";
22
+}

+ 58 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/form/GatewayRouteForm.java

@@ -0,0 +1,58 @@
1
+package com.yaozhitech.spring5.form;
2
+
3
+import java.util.ArrayList;
4
+import java.util.List;
5
+
6
+import javax.validation.constraints.NotBlank;
7
+import javax.validation.constraints.NotEmpty;
8
+
9
+import org.springframework.beans.BeanUtils;
10
+
11
+import com.fasterxml.jackson.core.JsonProcessingException;
12
+import com.fasterxml.jackson.databind.ObjectMapper;
13
+
14
+import io.swagger.annotations.ApiModel;
15
+import io.swagger.annotations.ApiModelProperty;
16
+import lombok.Data;
17
+import lombok.extern.slf4j.Slf4j;
18
+
19
+@ApiModel
20
+@Data
21
+@Slf4j
22
+public class GatewayRouteForm {
23
+
24
+    @NotEmpty(message = "网关断言不能为空")
25
+    @ApiModelProperty(value = "网关断言")
26
+    private List<PredicateDefinition> predicates = new ArrayList<>();
27
+
28
+    @ApiModelProperty(value = "网关过滤器信息")
29
+    private List<FilterDefinition> filters = new ArrayList<>();
30
+
31
+    @NotBlank(message = "uri不能为空")
32
+    @ApiModelProperty(value = "网关uri")
33
+    private String uri;
34
+
35
+    @NotBlank(message = "路由id不能为空")
36
+    @ApiModelProperty(value = "网关路由id")
37
+    private String routeId;
38
+
39
+    @ApiModelProperty(value = "排序")
40
+    private Integer orders = 0;
41
+
42
+    @ApiModelProperty(value = "网关路由描述信息")
43
+    private String description;
44
+
45
+    
46
+    public GatewayRoute toPo(Class<GatewayRoute> clazz) {
47
+        GatewayRoute gatewayRoute = new GatewayRoute();
48
+        BeanUtils.copyProperties(this, gatewayRoute);
49
+        try {
50
+            ObjectMapper objectMapper = new ObjectMapper();
51
+            gatewayRoute.setFilters(objectMapper.writeValueAsString(this.getFilters()));
52
+            gatewayRoute.setPredicates(objectMapper.writeValueAsString(this.getPredicates()));
53
+        } catch (JsonProcessingException e) {
54
+            log.error("网关filter或predicates配置转换异常", e);
55
+        }
56
+        return gatewayRoute;
57
+    }
58
+}

+ 29 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/form/GatewayRouteQueryForm.java

@@ -0,0 +1,29 @@
1
+package com.yaozhitech.spring5.form;
2
+
3
+import java.util.Date;
4
+
5
+import javax.validation.constraints.Past;
6
+
7
+import org.springframework.format.annotation.DateTimeFormat;
8
+
9
+import io.swagger.annotations.ApiModel;
10
+import io.swagger.annotations.ApiModelProperty;
11
+import lombok.Data;
12
+
13
+@ApiModel
14
+@Data
15
+public class GatewayRouteQueryForm {
16
+
17
+    @ApiModelProperty(value = "uri路径", required = true)
18
+    private String uri;
19
+
20
+    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
21
+    @Past(message = "查询开始时间必须小于当前日期")
22
+    @ApiModelProperty(value = "查询开始时间")
23
+    private Date createdTimeStart;
24
+
25
+    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
26
+    @Past(message = "查询结束时间必须小于当前日期")
27
+    @ApiModelProperty(value = "查询结束时间")
28
+    private Date createdTimeEnd;
29
+}

+ 16 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/form/PredicateDefinition.java

@@ -0,0 +1,16 @@
1
+package com.yaozhitech.spring5.form;
2
+
3
+import lombok.*;
4
+
5
+import java.util.LinkedHashMap;
6
+import java.util.Map;
7
+
8
+@EqualsAndHashCode
9
+@Data
10
+@Builder
11
+@NoArgsConstructor
12
+@AllArgsConstructor
13
+public class PredicateDefinition {
14
+    private String name;
15
+    private Map<String, String> args = new LinkedHashMap<>();
16
+}

+ 87 - 0
spring5-admin/src/main/java/com/yaozhitech/spring5/service/impl/GatewayRouteService.java

@@ -0,0 +1,87 @@
1
+package com.yaozhitech.spring5.service.impl;
2
+
3
+import java.io.IOException;
4
+import java.net.URI;
5
+import java.util.List;
6
+
7
+import org.springframework.cloud.gateway.route.RouteDefinition;
8
+import org.springframework.data.redis.core.RedisTemplate;
9
+import org.springframework.stereotype.Service;
10
+
11
+import com.fasterxml.jackson.core.type.TypeReference;
12
+import com.fasterxml.jackson.databind.ObjectMapper;
13
+import com.yaozhitech.spring5.form.FilterDefinition;
14
+import com.yaozhitech.spring5.form.GatewayRoute;
15
+import com.yaozhitech.spring5.form.PredicateDefinition;
16
+
17
+import lombok.extern.slf4j.Slf4j;
18
+
19
+@Service
20
+@Slf4j
21
+public class GatewayRouteService {
22
+
23
+    private static final String GATEWAY_ROUTES = "gateway_routes::";
24
+    
25
+    private RedisTemplate redisTemplate;
26
+
27
+//    @CreateCache(name = GATEWAY_ROUTES, cacheType = CacheType.REMOTE)
28
+//    private Cache<String, RouteDefinition> gatewayRouteCache;
29
+//
30
+//    @Autowired
31
+//    private EventSender eventSender;
32
+
33
+    public boolean add(GatewayRoute gatewayRoute) {
34
+//        boolean isSuccess = this.save(gatewayRoute);
35
+        // 转化为gateway需要的类型,缓存到redis, 并事件通知各网关应用
36
+        RouteDefinition routeDefinition = gatewayRouteToRouteDefinition(gatewayRoute);
37
+        
38
+        redisTemplate.opsForValue().set(gatewayRoute.getRouteId(), routeDefinition);
39
+//        eventSender.send(BusConfig.ROUTING_KEY, routeDefinition);
40
+        return true;
41
+    }
42
+
43
+//    public boolean delete(String id) {
44
+//        GatewayRoute gatewayRoute = this.getById(id);
45
+//        // 删除redis缓存, 并事件通知各网关应用
46
+//        gatewayRouteCache.remove(gatewayRoute.getRouteId());
47
+//        eventSender.send(BusConfig.ROUTING_KEY, gatewayRouteToRouteDefinition(gatewayRoute));
48
+//        return this.removeById(id);
49
+//    }
50
+//
51
+//    public boolean update(GatewayRoute gatewayRoute) {
52
+//        boolean isSuccess = this.updateById(gatewayRoute);
53
+//        // 转化为gateway需要的类型,缓存到redis, 并事件通知各网关应用
54
+//        RouteDefinition routeDefinition = gatewayRouteToRouteDefinition(gatewayRoute);
55
+//        gatewayRouteCache.put(gatewayRoute.getRouteId(), routeDefinition);
56
+//        eventSender.send(BusConfig.ROUTING_KEY, routeDefinition);
57
+//        return isSuccess;
58
+//    }
59
+//
60
+    /**
61
+     * 将数据库中json对象转换为网关需要的RouteDefinition对象
62
+     *
63
+     * @param gatewayRoute
64
+     * @return RouteDefinition
65
+     */
66
+    private RouteDefinition gatewayRouteToRouteDefinition(GatewayRoute gatewayRoute) {
67
+        RouteDefinition routeDefinition = new RouteDefinition();
68
+        routeDefinition.setId(gatewayRoute.getRouteId());
69
+        routeDefinition.setOrder(gatewayRoute.getOrders());
70
+        routeDefinition.setUri(URI.create(gatewayRoute.getUri()));
71
+        ObjectMapper objectMapper = new ObjectMapper();
72
+        try {
73
+            routeDefinition.setFilters(objectMapper.readValue(gatewayRoute.getFilters(), new TypeReference<List<FilterDefinition>>() {
74
+            }));
75
+            routeDefinition.setPredicates(objectMapper.readValue(gatewayRoute.getPredicates(), new TypeReference<List<PredicateDefinition>>() {
76
+            }));
77
+        } catch (IOException e) {
78
+            log.error("网关路由对象转换失败", e);
79
+        }
80
+        return routeDefinition;
81
+    }
82
+//
83
+//    public GatewayRoute get(String id) {
84
+//        return this.getById(id);
85
+//    }
86
+
87
+}

+ 1 - 7
spring5-auth/spring5-auth-client/pom.xml

@@ -6,7 +6,7 @@
6 6
 	<artifactId>spring5-auth-client</artifactId>
7 7
 	<packaging>jar</packaging>
8 8
 	<name>${project.artifactId}</name>
9
-    <description>spring5 demo</description>
9
+    <description>spring5 demo</description> 
10 10
 	
11 11
 	<parent>
12 12
         <groupId>com.yaozhitech</groupId>
@@ -21,12 +21,6 @@
21 21
 <!--             <artifactId>spring-boot-starter-data-redis-reactive</artifactId> -->
22 22
 <!--         </dependency> -->
23 23
         
24
-        <!-- Spring Boot Web 依赖 -->
25
-        <dependency>
26
-            <groupId>org.springframework.boot</groupId>
27
-            <artifactId>spring-boot-starter-web</artifactId>
28
-        </dependency>
29
-        
30 24
         <!-- jwt -->
31 25
         <dependency>
32 26
             <groupId>com.auth0</groupId>

+ 1 - 0
spring5-common/pom.xml

@@ -19,6 +19,7 @@
19 19
         <dependency>
20 20
             <groupId>org.springframework.boot</groupId>
21 21
             <artifactId>spring-boot-starter-web</artifactId>
22
+            <exclusions></exclusions>
22 23
         </dependency>
23 24
 		
24 25
 	</dependencies>