搭建服务环境
在spring-cloud-demo工程中添加module:demo-feign-consumer
在pom.xml文件中加入依赖:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
</dependencies>
在resource目录下增加application.properties文件,添加如下内容:
################## 服务配置 ###############
server.port=9257
spring.application.name=demo-feign-consumer
#注册到注册中心
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/,http://localhost:8762/eureka/
创建一个启动类:FeignConsumerApplication.java,添加如下内容:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class FeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(FeignConsumerApplication.class, args);
}
}
添加Service类:DemoFeignService.java,添加如下内容:
@FeignClient(value = "demo-service")
public interface DemoFeignService {
@RequestMapping(value = "/port", method = RequestMethod.GET)
String hello();
}
添加Controller类:DemoFeignController.java,添加如下内容:
@RestController
public class DemoFeignController {
@Autowired
DemoFeignService demoFeignService;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String port() {
return demoFeignService.hello();
}
}
分别使用9806、9807端口运行之前构建的demo-service工程
运行demo-feign-consumer项目,访问http://localhost:9257/hello,显示如下:
I am demo-service, I'm from port : 9808
如此实现了服务的声明式调用,多次访问按次序返回不同的端口,说明负载均衡已经实现,使用 默认使用的是轮询策略
负载均衡配置
在启动类文件FeignConsumerApplication.java中加入方法:
//新增随机策略
@Bean
public IRule ribbonRule() {
return new RandomRule(); //这里选择随机策略,对应配置文件
}
分别使用9806、9807端口运行之前构建的demo-service工程
再运行demo-feign-consumer项目,访问:http://localhost:9257/hello,多访问几次就会发现返回的端口就是随机的了
I am demo-service, I'm from port : 9806
I am demo-service, I'm from port : 9806
I am demo-service, I'm from port : 9806
I am demo-service, I'm from port : 9807