欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【spring cloud (二)】spring boot+spring cloud+nacos+gateway+ribbon负载均衡配置

程序员文章站 2024-03-20 22:28:16
...

1.新建gateway工程,pom文件引入配置


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


<!--服务发现、注册-->
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

<!--jwt-->
<dependency>
   <groupId>io.jsonwebtoken</groupId>
   <artifactId>jjwt</artifactId>
   <version>0.9.0</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>1.7.26</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>1.7.26</version>
   <scope>test</scope>
</dependency>
 
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

2.配置文件 application.yml

server:
  port: 9527
spring:
  application:
    name: service-getway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true # 开启从注册中心动态创建路由的功能,利用微服务名称j进行路由
      routes:
        - id: routep #路由的id
          uri: lb://jk-nacos-provider  #服务名称
          predicates:
            - Path=/person/**
    nacos:
      discovery:
        server-addr: nacos-server-02:8848,nacos-server-03:8848
        namespace: b3845fc3-ceea-4a96-bd4f-c7a7541f0485
#自定义负载均衡册罗 默认轮询 设置为随机
#      jk-nacos-provider   服务名称
jk-nacos-provider:
  ribbon:
    listOfServers: localhost:8083, localhost:8081
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

3.启动类添加 @EnableDiscoveryClient 注解,注解到nacos服务中
【spring cloud (二)】spring boot+spring cloud+nacos+gateway+ribbon负载均衡配置4.新建一个服务提供者工程,一个简单的能对外提供服务的spring boot工程就可以。配置文件:


spring:
  application:
    name: jk-nacos-provider
  cloud:
    nacos:
      discovery:
        server-addr: nacos-server-02:8848,nacos-server-03:8848
        namespace: b3845fc3-ceea-4a96-bd4f-c7a7541f0485
server:
  port: 8081

5.启动类添加注解:@EnableDiscoveryClient,注册到服务中心
【spring cloud (二)】spring boot+spring cloud+nacos+gateway+ribbon负载均衡配置
6.新建一个controller类对外提供服务
【spring cloud (二)】spring boot+spring cloud+nacos+gateway+ribbon负载均衡配置
7.在idea中启动两个服务,端口分别是8081和8083

8.访问网关gateway路径,进行测试:http://localhost:9527/person/getPerson/test,随机访问到了不同端口提供的服务

相关标签: spring cloud