为什么会出现Feign?负载均衡之前不是有Ribbon了吗?
我们之前实现的负载均衡是使用的Ribbon+RestTemplate,在controller中使用RestTemplate根据url去访问服务提供者,而通常我们是在controller中调用我们声明好的service实例去调用我们的逻辑,这样就不符合我们平时面向编程的规范了,所以feign的出现就是解决这个规范问题的。
我们还是基于之前的项目,新建名称为eureka-server-consumer-feign的module,在pom.xml加上feign,ribbon和eureka的依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
新建service包,在里面新建ITestService接口,加上@FeignClient注解。其中name属性为该service是调用哪一组服务提供者的。
@FeignClient(name = "EUREKA-SERVER-PROVIDER")
public interface ITestService {
@RequestMapping("/provider/test")
String test();
}
controller中引入ITestService:
@RestController
public class ConsumerController {
@Autowired
private ITestService iTestService;
@RequestMapping("/consumer/test3")
public String test3(){
return iTestService.test();
}
}
启动类,加上@EnableFeignClients注解,@EnableEurekaClient注解,@EnableDiscoveryClient注解:
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
@EnableDiscoveryClient
public class EurekaServerConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerConsumerFeignApplication.class, args);
}
}
配置文件application.yml:
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/,http://localhost:7003/eureka/
启动Eureka集群7001,7002和7003,服务提供者8001,8002和8003,以及我们上面的消费者feign
结果发现,利用feign也成功实现了负载均衡,其实feign中就是集成了Ribbon的特性。
扫描二维码关注公众号,回复:
11851328 查看本文章