SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合

项目链接地址:
链接:https://pan.baidu.com/s/1NbP71A7xLzriM5BKo5L_yQ
提取码:ljl6

版本:
SpringBoot:2.6.5
SpringCloud:2021.0.3
SpringGateway:2021.0.3
nacos:2021.1
loadbalancer:3.1.3

版本原因,loadbalancer依赖是要加入的,要不然对应的gateway网关配置lb负载平衡会报错。

夹杂私货,这是我的另一篇文章,提供了一些基础类,比如用户,订单,或者直接网盘下载。这两篇文章不同在于注册中心,一个是eureka,一个是nacos。
https://blog.csdn.net/qq_44327755/article/details/126036882

正式开始
主要涉及3个模块分别是userservice,orderservice,springcloud_gateway
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第1张图片
springcloud_gateway:

SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第2张图片
pom.xml

 <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2021.0.3</spring-cloud.version>
        <nacos.version>2021.1</nacos.version>
        <loadbalancer.version>3.1.3</loadbalancer.version>
 </properties>
 <dependencies>  
 <!--spring-boot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!--spring-cloud-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <!--nacos依赖服务注册-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>${nacos.version}</version>
        </dependency>

        <!--gateway-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <!--loadbalancer -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
            <version>${loadbalancer.version}</version>
        </dependency>

        <!--test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
   </dependencies>  

CrossConfig是解决跨域问题

@Configuration
public class CrossConfig {

    @Bean
    public CorsWebFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsWebFilter(source);
    }

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //在生产环境上最好指定域名,以免产生跨域安全问题
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }
}

配置:

spring:
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
      routes:
      - id: user-service
        uri: lb://UserServiceProvider
        predicates:
          - Path=/userServer/**
        filters:
          - StripPrefix=1
          - PrefixPath=/userServer
      - id: order-service
        uri: lb://OrderServiceConsumer
        predicates:
          - Path=/orderServer/**
        filters:
          - StripPrefix=1
          - PrefixPath=/orderServer

启动类添加注解**@EnableDiscoveryClient**
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第3张图片

userservice–这里只展示红色箭头内容
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第4张图片
pom.xml(这里提供的依赖不一定完整,根据情况调整,可以网盘直接下载,也可以了解大概思路)

 <properties>
        <java.version>1.8</java.version>
        <spring-boot.version>2.6.5</spring-boot.version>
        <spring-cloud.version>2021.0.3</spring-cloud.version>
        <mysql.vesrion>8.0.23</mysql.vesrion>
        <druid.version>1.2.6</druid.version>
        <mybatis.version>2.2.0</mybatis.version>
        <lombok.version>1.18.24</lombok.version>
        <nacos.version>2021.1</nacos.version>             	
        <loadbalancer.version>3.1.3</loadbalancer.version>
    </properties>
  <dependencies>
  <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.vesrion}</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.logging.log4j</groupId>
                    <artifactId>log4j-to-slf4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

 <!--nacos依赖服务注册-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>${nacos.version}</version>
        </dependency>

        <!--loadbalancer-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-loadbalancer</artifactId>
            <version>${loadbalancer.version}</version>
        </dependency>


        <!--openfeign依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

yaml(配置mvc是因为springboot和swagger版本问题,这里不涉及,你也可以忽略)

server:
  port: 8081

spring:
  application:
    name: UserServiceProvider
  datasource:
    druid:
      url: jdbc:mysql://127.0.0.1:3306/spring-cloud-demo?serverTimezone=GMT%2B8
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: 1234
      max-active: 100
      max-wait: 60000
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

mybatis:
  mapper-locations:  classpath:mapper/*.xml
  type-aliases-package: com.practice.entity
  configuration:
    map-underscore-to-camel-case: true

  pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: false
    params: count=countSql

feign:
  circuitbreaker:
    enabled: true

orderclient(因为想调用order的服务)

@FeignClient(name = "OrderServiceConsumer/orderServer",contextId = "orderServer")
public interface OrderClient {

    /**
     *@Param: @param Integer user_id:
     *@return: List<Order>
     *@Description:根据用户ID查找订单
     */
    @GetMapping("/getByUserId")
    List<Order> findByUserId(@RequestParam("user_id") Integer user_id);
}

SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第5张图片
对应orderController里面的,要不然或许访问会报错,找不着路径,血泪的教训
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第6张图片
userController:

@RestController("userServer")
@RequestMapping("/userServer")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderClient orderClient;

    @ApiOperation("根据ID查找用户")
    @GetMapping("/findById")
    public User getById(Integer id){
        User user = userService.findUserById(id);
        return  user;
    }

    @ApiOperation("查找所有用户")
    @GetMapping("/findAll")
    public List<User> get(){
        return userService.findAllUser();
    }



    @ApiOperation("根据订单查找用户")
    @GetMapping("/findByOrder")
    public User getByOrder(Integer order_id){
        return userService.findByOrder(order_id);
    }


    //测试orderClient
    @ApiOperation("根据用户ID查找订单")
    @GetMapping("/getByUserId")
    public List<Order> findByUserId(Integer user_id){
        return  orderClient.findByUserId(user_id);
    }


}

SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第7张图片
启动类添加注解@EnableFeignClients@EnableDiscoveryClient
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第8张图片
orderservice和userService类似
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第9张图片
pom.xml和上面的一样(因为我这里order user 同时是服务提供者和消费者)
yaml:

server:
  port: 8086

spring:
  application:
    name: OrderServiceConsumer
  datasource:
    druid:
      url: jdbc:mysql://127.0.0.1:3306/spring-cloud-demo?serverTimezone=GMT%2B8
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: 1234
      max-active: 100
      max-wait: 60000
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848



mybatis:
  mapper-locations:  classpath:mapper/*.xml
  type-aliases-package: com.practice.entity
  configuration:
    map-underscore-to-camel-case: true

  pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: false
    params: count=countSql

feign:
  circuitbreaker:
    enabled: true

userClient:

@FeignClient(name = "UserServiceProvider/userServer",contextId = "userServer")
public interface UserClient {


    /**
     *@Param: @param id:
     *@return: User
     *@Description: 根据订单查找用户
     */
    @GetMapping("/findByOrder")
    User findUserByOrder(@RequestParam("order_id")Integer order_id);
}

SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第10张图片
OrderController:

@RestController("orderServer")
@RequestMapping("/orderServer")
@Api(tags = "订单管理")
public class OrderController {


    @Autowired
    private OrderService orderService;

    @Autowired
    private UserClient userClient;

    @ApiOperation("根据ID查找订单")
    @GetMapping("/getById")
    public Order findById(Integer id){
        return  orderService.findById(id);
    }

    @ApiOperation("查找所有订单")
    @GetMapping("/getAll")
    public List<Order> findAll(){
        return  orderService.findAllOrder();
    }



    @ApiOperation("根据用户姓名查找订单")
    @GetMapping("/getByUserName")
    public List<Order> findByUserName(String user_name){
        return  orderService.findUserByName(user_name);
    }


    @ApiOperation("根据用户ID查找订单")
    @GetMapping("/getByUserId")
    public List<Order> findByUserId(Integer user_id){
        return  orderService.findByUserId(user_id);
    }

    //测试userClient

    @ApiOperation("根据订单查找用户")
    @GetMapping("/findByOrder")
    public User getByOrder(@RequestParam("order_id") Integer order_id){
        return userClient.findUserByOrder(order_id);
    }

}

启动类加注解@EnableFeignClients@EnableDiscoveryClient
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第11张图片
结果证明:
加入网关后,各个端口正常
8081用户
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第12张图片
8086订单
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第13张图片
88网关
在这里插入图片描述
测试三种方式实现统一目标–通过订单号查询用户
1):88网关
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第14张图片
2):8086订单(涉及订单远端调用RPC用户–openfeign)
SpringBoot+SpringCloud+SpringGateway+OpenFeign+Nacos整合_第15张图片
提示:
如果只是参考这里的代码可能会报错,但是可以从中了解大体思路
也可以实现通过用户ID查询订单信息(涉及用户RPC订单)
在这里插入图片描述
在这里插入图片描述

你可能感兴趣的:(SSM学习笔记,spring,cloud,spring,boot,java)