微服務中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作服務降級處理》。html

如何加入Feign

第一步
加入feign的Jarjava

<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.ymlweb

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客戶端接口spring

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老師提供支持,感謝!架構

相關文章
相關標籤/搜索