1、概念
(1)概述
Feign是一个声明式的Web服务客户端,使得编写Web服务客户端变得非常容易,只需要创建一个接口,然后在上面添加注解即可,能够实现客户端的负载均衡。
2、Feign工程构建
(1)模仿消费者(80)新建一个Feign模块,并添加Feign的依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
(2)修改公共模块
- 添加Feign的依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
- 创建接口
注解的参数中带有微服务的名称,通过该名称获取服务
@FeignClient(value = "PROVIDER") public interface DeptClientService { @RequestMapping(value = "/dept/get/{id}",method = RequestMethod.GET) public Dept get(@PathVariable("id") long id); @RequestMapping(value = "/dept/list",method = RequestMethod.GET) public List<Dept> list(); @RequestMapping(value = "/dept/add",method = RequestMethod.POST) public boolean add(Dept dept); }
(3)创建消费者模块
@RestController public class DeptConsumerController { @Autowired private DeptClientService service = null; @RequestMapping(value = "/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return this.service.get(id); } @RequestMapping(value = "/consumer/dept/list") public List<Dept> list() { return this.service.list(); } @RequestMapping(value = "/consumer/dept/add") public Object add(Dept dept) { return this.service.add(dept); } }
- 启动类
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}) @EnableEurekaClient @EnableFeignClients(basePackages= {"com.zhb"}) @ComponentScan("com.zhb") public class DeptConsumer80_Feign_App { public static void main(String[] args) { SpringApplication.run(DeptConsumer80_Feign_App.class,args); } }
(4)RestTemplate 方式
消费者模块代码:
与Feign相比,RestTemplate 方式不需要在公共类里面添加接口,Feign是在接口里面的注解添加微服务的名称即可。
@RestController public class DeptConsumerController { private static final String REST_URL_PREFIX = "http://PROVIDER"; @Autowired private RestTemplate restTemplate; @RequestMapping(value = "/consumer/dept/add") public boolean add(Dept dept) { return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class); } @RequestMapping(value = "/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class); } @SuppressWarnings("unchecked") @RequestMapping(value = "/consumer/dept/list") public List<Dept> list() { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class); } }
配置类:
@Bean @LoadBalanced public RestTemplate template(){ return new RestTemplate(); }
(5)负载均衡
Feign集成了Ribbon,并通过轮询的方式实现了客户端的负载均衡