1.首先配置模块的pom文件,引入openFeign
<dependencies>
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--eureka-client 已经集成了ribbon复杂均衡-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.配置application.yml文件
server:
port: 80
eureka:
client:
#true表示将自己注册进eureka server
register-with-eureka: false
#true默认值,从eureka server抓取已有的注册信息,单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetch-registry: true
service-url:
#defaultZone: http://localhost:7001/eureka/
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka
#配置主机名称
instance:
instance-id: consumerfeignorder80
prefer-ip-address: true
3.主启动类,必须使用@EnableFeignClients注解,激活feign
@SpringBootApplication
@EnableFeignClients//使用feign并开启激活
public class ConsumerFeignOrderMain {
public static void main(String[] args) {
SpringApplication.run(ConsumerFeignOrderMain.class,args);
}
}
4.新建一个service接口
openFeign是基于接口调用微服务的,所以在业务接口添加注解@FeignClient并制定微服务的名称,以此来实现负载均衡调用
@ComponentScan
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping("/payment/get/{id}")
CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
5.新建controller调用service
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return paymentFeignService.getPaymentById(id);
}
}
基于openfeign的负载均衡就搭建好了
OpenFeign负载均衡实践
本文详细介绍如何通过OpenFeign实现微服务之间的负载均衡。包括配置pom文件引入依赖、设置application.yml参数、使用@EnableFeignClients注解激活Feign、创建Service接口以及Controller等步骤。

181

被折叠的 条评论
为什么被折叠?



