微服务中Feign快速搭建

在微服务架构搭建声明性REST客户端【feign】。
Feign是一个声明式的Web服务客户端。这使得Web服务客户端的写入更加方便 要使用Feign创建一个界面并对其进行注释。它具有可插入注释支持,包括Feign注释和JAX-RS注释。Spring Cloud增加了对Spring MVC注释的支持,并使用Spring Web中默认使用的HttpMessageConverters。Spring Cloud集成Ribbon和Eureka以在使用Feign时提供负载均衡的http客户端。

有关Feign做微服务降级处理的文章请看上海尚学堂《Hystrix在Fegin做服务降级处理》。

如何加入Feign

第一步
加入feign的Jar

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
 </dependency>
 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
 </dependency>
 <dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
 </dependency>

第二步
 
修改配置文件application.yml

spring:
  application:
    name: microservice-consumer-movie
server:
  port: 7901
eureka:
  client:
    healthcheck:
      enabled: true
     serviceUrl:
      defaultZone: http://user:password123@localhost:8761/eureka
   instance:
    prefer-ip-address: true

  

第三步
 
添加fegin客户端接口

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 org.yonggan.entity.User;

 @FeignClient("microservice-provider-user") // 服务名称
public interface UserFeignClient {

     @RequestMapping(value = "/simple/{id}" ,method = RequestMethod.GET)
     User findById(@PathVariable("id") Long id);
 }

  

第四步
 
添加fegin 接口注入到我们web接口层那使用。

@RestController
 public class MovieController {
     /**
     *   添加fegin 远程的客户端
     *   了解更多微信:java8733
     */
     @Autowired
     private UserFeignClient feignClient;

     @GetMapping("/movie/{id}")
     public User findById(@PathVariable Long id) {
         return feignClient.findById(id);
     }
 }

  

 
上述就是我们快速的搭建Fegin环境的demo,由上海尚学堂java老师提供支持,感谢!

原文地址:https://www.cnblogs.com/shsxt/p/8177233.html