Spring Cloud服务接入

    接入前,请正确启动 shenyu-admin,并开启springCloud插件,在网关端和springCloud服务端引入相关依赖。可以参考前面的 Spring Cloud快速开始

    应用客户端接入的相关配置请参考:。

    数据同步的相关配置请参考:数据同步配置

    • 在网关的 pom.xml 文件中引入如下依赖。
    • 如果你使用 eureka 作为 springCloud的注册中心

      • 在网关的pom.xml文件中,新增如下依赖:
      1. <dependency>
      2. <groupId>org.springframework.cloud</groupId>
      3. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
      4. <version>2.2.0.RELEASE</version>
      5. </dependency>
    • 在网关的yml文件中,新增如下配置:

      1. eureka:
      2. client:
      3. serviceUrl:
      4. defaultZone: http://localhost:8761/eureka/ # 你的eureka地址
      5. instance:
      6. prefer-ip-address: true
      • 在网关的pom.xml文件中,新增如下依赖:
    • 在网关的yml文件中 新增如下配置:

      1. spring:
      2. cloud:
      3. nacos:
      4. discovery:
    • 重启你的网关服务。

    可以参考:

    • 在由构建的微服务中,引入如下依赖:
    1. <dependency>
    2. <groupId>org.apache.shenyu</groupId>
    3. <artifactId>shenyu-spring-boot-starter-client-springcloud</artifactId>
    4. <version>${shenyu.version}</version>
    5. </dependency>
    • controller接口上加上 @ShenyuSpringCloudClient 注解。 注解可以加到类或方法上面,path属性为前缀,如果含有 /** 代表你的整个接口需要被网关代理。

    • 示例一: 代表 /test/payment, /test/findByUserId 都会被网关代理。

    1. * 示例二:
    2. 代表 `/order/save`,会被网关代理,而`/order/findById` 则不会。
    3. ```java
    4. @RestController
    5. @RequestMapping("/order")
    6. @ShenyuSpringCloudClient(path = "/order")
    7. public class OrderController {
    8. @PostMapping("/save")
    9. @ShenyuSpringMvcClient(path = "/save")
    10. public OrderDTO save(@RequestBody final OrderDTO orderDTO) {
    11. orderDTO.setName("hello world save order");
    12. }
    13. @GetMapping("/findById")
    14. public OrderDTO findById(@RequestParam("id") final String id) {
    15. orderDTO.setId(id);
    16. orderDTO.setName("hello world findById");
    17. return orderDTO;
    18. }
    19. }
    • 示例三: isFulltrue 代表整个服务都会被网关代理。
    1. shenyu:
    2. client:
    3. registerType: http
    4. serverLists: http://localhost:9095
    5. props:
    6. contextPath: /http
    7. appName: http
    8. isFull: true
    9. # registerType : 服务注册类型,请参考应用客户端接入文档
    10. # serverList: 服务列表,请参考应用客户端接入文档
    11. # contextPath: 为你的项目在shenyu网关的路由前缀。 比如/order ,/product 等等,网关会根据你的这个前缀来进行路由。
    12. # appName:你的应用名称,不配置的话,会默认取application 中的名称
    13. # isFull: 设置true 代表代理你的整个服务,false表示代理你其中某几个controller
    • 启动你的服务成功注册后,进入后台管理系统的插件列表 -> rpc proxy -> springCloud,会看到自动注册的选择器和规则信息。

    和之前的访问方式没有大的改变,需要注意的是:

    • 网关需要有一个路由前缀,这个路由前缀就是你接入项目进行配置 contextPath,可以在 shenyu-admin 中的 springCloud插件进行更改。