03. Feign

03. Feign

Feign使用面向api编程, 来简化编程 ,默认使用RoundRobbin,可以不需要额外配置负载均衡

在ribbon的基础上修改

  1. microsoft-api
  • 修改api的pom.xml添加

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
    
  • 添加一个接口

    //name对应微服务名称
    @FeignClient("MICROSOFT-PROVIDER")
    public interface DeptClientService {
        //表示发送/provider/add请求到MICROSOFT-PROVIDER所在的服务
        @PostMapping(path = {"/provider/add"})
        boolean add(@RequestBody Dept dept);
    
        @GetMapping(path = "/provider/get/{id}")
         Dept get(@PathVariable("id") Integer id);
    
        @GetMapping(path = "/provider/get")
         List<Dept> list();
    }
    
  1. 添加一个模块, 将consumer拷贝
  • 添加依赖

            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
    
  • 修改controller

    @RestController
    @RequestMapping("/consumer")
    public class DeptConsumerController {
        @Autowired
        DeptClientService service;
        //controller中的mapping可以与接口中定义的不同,但是api接口中的mapping要与微服务定义的mapping相同
        @PostMapping(path = {"/add"})
        public boolean add(@RequestBody Dept dept){
            return service.add(dept);
        }
        @GetMapping(path = "/get/{id}")
        public Dept get(@PathVariable("id") Integer id){
            return service.get(id);
        }
    
        @GetMapping(path = "/get")
        public List<Dept> list(){
            return service.list();
        }
    }
    
  • 修改主启动类

    //扫描对应@FeignClient修饰的接口所在包
    @EnableFeignClients({"com.chz.microsoftapi.service"})
    @EnableEurekaClient
    @SpringBootApplication
    public class MicrosoftConsumer80FeignApplication {
    
    	public static void main(String[] args) {
    		SpringApplication.run(MicrosoftConsumer80FeignApplication.class, args);
    	}
    }
    

    如果使用RoundRobbin来负载均衡就行, 那么就不用配置Ribbon

posted @ 2020-05-11 14:08  CyberPelican  阅读(79)  评论(0编辑  收藏  举报