美文网首页
SpringCloud---Feign(消费端的调用框架)

SpringCloud---Feign(消费端的调用框架)

作者: RalapHao | 来源:发表于2017-10-30 23:48 被阅读0次

    介绍

    Feign是一个公开的Web服务客户端。它使编写Web服务客户机更容易。用Feign创建接口和注释。它具有可拔插的注释支持,包括Feign的注释和JAX-RS注释。Feign还支持热插拔编码器和解码器。Spring Cloud添加注释的支持和使用Spring MVC的Spring Web默认使用相同的httpmessageconverters。springCloud集成了Ribbon和Eureka提供负载平衡的HTTP客户端使用Feign

    简单使用(Spring mvc的注解)

    1. 启动类添加@EnableFeignClients注解
    @SpringBootApplication
    @EnableEurekaClient
    @EnableFeignClients
    public class MovieFeignApplication {
    
      public static void main(String[] args) {
          SpringApplication.run(MovieFeignApplication.class, args);
      }
    }
    
    1. 创建Client,是用Spring mvc注解
    //user-provider是服务提供者user的applicationName
    @FeignClient("user-provider")
    public interface UserClient {
        @RequestMapping(value = "/getUser/{id}", method = RequestMethod.GET)
        User getUser(@PathVariable(value = "id") Integer id);
    
        @RequestMapping(value = "/changeUser", method = RequestMethod.POST)
        User changeUser(@RequestBody User user);
    
    }
    

    这里需要注意一下:

    1. RequestMapping不能使用GetMapping代替;
      》2. @PathVariable中必须给出明确的value值;
    1. 调用
    @RestController
    public class MovieController {
    
        @Autowired
        private UserClient userClient;
    
        @GetMapping("/movie/{id}")
        public User getUser(@PathVariable Integer id) {
            return userClient.getUser(id);
        }
    
        @GetMapping(value = "/changeUser")
        public User chanageUser(User user) {
            return userClient.changeUser(user);
        }
    }
    
    

    使用Feign的注解

    1. 添加Configration类
    @Configuration
    public class FooConfigration {
    
        @Bean
        public Contract feignContract() {
            return new feign.Contract.Default();
        }
    }
    
    1. 修改 Client类
    @FeignClient(name = "user-provider", configuration = FooConfigration.class)
    public interface UserClient {
    
    //    @RequestMapping(value = "/getUser/{id}", method = RequestMethod.GET)
    //    User getUser(@PathVariable(value = "id") Integer id);
    
    //    @RequestMapping(value = "/changeUser", method = RequestMethod.POST)
    //    User changeUser(@RequestBody User user);
    
    
        @RequestLine("GET /getUser/{id}")
        User getUser(@Param("id") Integer id);
    
    }
    
    1. 修改@FeignClient(name = "user-provider", configuration = FooConfigration.class);
    2. 使用Fegin的注解 @RequestLine("GET /getUser/{id}")
    3. 使用Fegin 的注解@Param

    相关文章

      网友评论

          本文标题:SpringCloud---Feign(消费端的调用框架)

          本文链接:https://www.haomeiwen.com/subject/bqxvpxtx.html