前言
之前作业是使用 nacos注册中心来搭建有一个微服务,消费者必然要用到gateway网关来操作路由,并且配置负载均衡策略。
搭建微服务-文章链接:快速搭建微服务-Nacos_一码超人的博客-CSDN博客_微服务搭建nacos
添加一个gateway模块
配置文件application.yml
server:
port: 8877
spring:
application:
name: java-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
# 结合nacos
discovery:
locator:
enabled: true
routes:
- id: java-provider # 标识,这里写了服务名城管
uri: lb://java-provider # nacos中调用的服务名称
predicates:
- Path=/java/** # 简化路由,将java-provider改为java
filters:
- StripPrefix=1
访问服务:http://127.0.0.1:8877/java/**
默认是轮询策略,loadbalancer有两种策略,一个是轮询一个便是随机。关于权重策略可以在nacos后台进行修改 。
修改为随机策略,添加配置类。
package com.example.gateway.config;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
public class LoadBalancerConfig {
@Bean
ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RandomLoadBalancer(loadBalancerClientFactory
.getLazyProvider(name, ServiceInstanceListSupplier.class),
name);
}
}
启动类,添加注解。
package com.example.gateway;
import com.example.gateway.config.LoadBalancerConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
@SpringBootApplication
@LoadBalancerClients(defaultConfiguration = LoadBalancerConfig.class)
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
测试结果