什么是Feign
- Feign是一个声明试WebService客户端,使得编写Web服务客户端变得非常容易。
- 只需要创建一个接口,然后在上面添加注解即可。(因为Feign实现了ribbon)
- 功能和ribbon一样,用来负载均衡
修改API模块
- cloud_api项目pom增加
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> - 增加接口DeptClientService,之所以放在API是因为其他的项目可以共享
package com.hongdou.service; import com.hongdou.entity.Dept; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import java.util.List; @FeignClient(value = "CLOUD-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); } - 重新maven clean、 maven install
增加客户端项目
- 搭建consumer_feifn_dept(复制consumer_dept)
- pom增加
<!-- feign相关 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> - 修改controller
package com.springcloud.controller; import com.hongdou.entity.Dept; import com.hongdou.service.DeptClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("consumer") public class DeptController { @Autowired private DeptClientService deptClientService; @GetMapping("/dept/add") public boolean add(Dept dept){ return deptClientService.add(dept); } @GetMapping(value = "/dept/get/{id}") public Dept get(@PathVariable("id") Long id){ Dept dept = deptClientService.get(id); return dept; } @GetMapping("/dept/list") public List<Dept> list(){ return deptClientService.list(); } } - 启动项增加@EnableFeignClients和@ComponentScan
@SpringBootApplication @EnableEurekaClient @EnableFeignClients(basePackages = {"com.hongdou"}) //一个是扫描api项目,一个是本项目的扫描 @ComponentScan(basePackages = {"com.hongdou", "com.springcloud"}) public class ConsumerFeignDept { public static void main(String[] args) { SpringApplication.run(ConsumerFeignDept.class, args); } } - 测试:先启动三个eureka注册中心,在启动三个cloud_provide服务端,最后启动consumer_feign_dept客户端。
- 结果:正常轮询后台服务,达到了负载均衡作用。
git地址:git@gitee.com:Xiaokeworksveryhard/spring_cloud.git
304

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



