0-前言
eureka实际上已经集成了负载均衡调度框架Ribbon;
我们有了各个微服务了,那怎么来调用他们呢,一种方法是可以使用 RestTemplate(如:String str= restTemplate.getForObject(“http://localhost:8763/user/hello”,String.class);
使用RestTemplate的话要使用负载均衡调度(ribbon)需要增加@LoadBalanced注解,如:
@Bean
@LoadBalanced
RestTemplate restTemplate()
{
return new RestTemplate();
}
但是,我们一般不会这样用,我们更希望像调用本地方法一样来调用其他微服务;这时候,Feign就粉末登场了
Feign:声明式服务调用,它使得我们调用其他微服务,就像调用本地方法一样;它默认使用Ribbon实现负载均衡;
1-Feign的使用
1、1、添加依赖
<!-- 声明式调用 feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
1、2、添加接口
其中name实需要调用的已经注册到eureka的微服务的名称;方法跟要调用的微服务方法一致,只包含声明,不包含实现
package com.anson.service.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "user")
public interface FUserService
{
@RequestMapping("/user/hello")
public String hello();
}
1、3、调用
@Autowired
private FUserService fUserService;
@RequestMapping("/order2")
public String order2()
{
return fUserService.hello();
}
是不是就像调用本地方法一样简单了;
1.4、运行测试
我们把eureka server项目、user项目(服务提供者)、order项目(服务消费者)依次启动;其中user启动了两个实例,
然后运行 http://localhost:8766/order/order2 ,多刷新几次
可以看到,Feign已成功执行,并且通过默认使用的Ribbon实现了负载均衡;
简单使用就这么简答,更深入的后续再详聊,GIT源码后续再放出