【SpringCloud】 Feign

1. What is

  feign a web service client declarative, it allows calls between micro-services become more simple, just need to create an interface, the interface can be above annotated @FeignClient, similar controller calling service. Feign with Ribbon and Eureka can support load balancing

2. What do

  Make writing Java Http client easier, it is to define and implement the service interface definitions depend, in addition Feign notes for the service to complete the above interfaces interface binding on the service provider. Feign interface method by calling Rest Services (equivalent Ribbon + RestTemplate), the request is sent to the Eureka server, find the service interface directly through Feign, due to the time during service calls combines Ribbon technology, it also supports load balancing. (Feing interview Interface, Ribbon for RestTemplate)

3. Why Feign

  Simple and can be custom encoder and an error process (there are other techniques Apache HttpClient, Jersey, and use these to write a CXF Rest or SOAP end customer java services)

4. Feign principle

  1. At startup, the program package will be scanned, scan all packets and all @FeignClient annotated classes, these classes and injected into the vessel IOC in spring. When defining the interface in Feign is called to generate a dynamic proxy RequestTemplate by the JDK.
  2. RequestTemplate all the information contained in the request, such as request parameters, the request URL and the like.
  3. RequestTemplate statement Request, then the Request to the client process, the client's default JDK HTTPUrlConnection, can also be OKhttp, Apache's HTTPClient etc.
  4. Finally client packaged as LoadBaLanceClient, combined with load balancing ribbon initiated calls

For more, see: https://xli1224.github.io/2017/09/22/configure-feign/

5. Project Application

5.1 Service Provider

5.1.1 lead dependence

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

5.1.2 Profile

feign:
  client:
    config:
      default:
        connectTimeout: 5000
        readTimeout: 5000
        loggerLevel: basic

5.1.3 Startup Items annotated

@EnableEurekaClient
@SpringBootApplication
@EnableDiscoveryClient
public class GameWebApplication {

    public static void main(String[] args){
        SpringApplication.run(GameWebApplication.class,args);
    }
}

5.1.4 Foreign storm drain service interface to add notes

package com.dmsdbj.integral.game.api.facade;

@FeignClient(value = "INTEGRAL-GAME-PROVIDER", path = "/game-web")
public interface LotteryClientService {

    @PostMapping(value = "/api/lottery/addLottery")
    IntegralResult<LotteryModel> addLottery(@RequestBody LotteryModel model);

}

Such re-registration of eureka call other services, like in the code to call his service as a

@FeignClient annotation attributes:

Property name Defaults effect Remark
value Null character bed Call the service name, and the name attribute the same
path Null character bed RequestMapping automatically to the front in all methods prefix, similar to the upper controller class requestMapping
serviceId Null character bed Service id, and the role of the same name attribute
name Null character bed Call the service name, and the same property value
url Null character bed Full path address or hostname, http or https optional
decode404 false Should Configuration Response status code 404 is thrown FeignExceptions
configuration {} The current custom of some configuration feign client
fallback void.class Fusing mechanism, the call fails, some of the go fallback method can be used to throw an exception or return data given default Underlying dependence hystrix, start to add class @EnableHystrix
primary true

5.2 Consumer Services

5.2.1 The dependence

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-openfeign</artifactId>
	<version>2.0.1.RELEASE</version>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
	<version>2.0.1.RELEASE</version>
</dependency>

5.2.2 Profile

eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://192.168.22.126:7001/eureka

5.2.3 Startup Items annotated

@EnableEurekaClient
// 服务发现
@EnableDiscoveryClient
// 对外暴漏接口所在的包路径
@EnableFeignClients(basePackages = " com.dmsdbj.integral.game.api.facade")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class InternApplication {
	public static void main(String[] args) {
		SpringApplication.run(InternApplication.class, args);
	}
} 

5.2.4 Consumer reference external service

//这里直接注入Feign client
@Autowired
private LotteryClientService   lotteryClientService;

@PostMapping("/toCart/{productId}")
public ResponseEntity addCart(@RequestBody LotteryModel model){
	// 调用注入服务的方法即可
     lotteryClientService.addLottery(model);
}

  Feign underlying default send HTTP requests using the jdk HttpURLConnection, feign bottom ribbon is used as client load balancing, load balancing and ribbon are dependent on each service address obtained eureka

6. problems encountered

In bebug mode debugging, the connection timeout occurs, you can do the following configuration in the configuration file:

ribbon:
  ConnectTimeout: 60000  # 连接超时时间
  ReadTimeout: 60000 # 超时时间
  ## 上面就可以解决此问题,下面配置作为扩展
   NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule  # Ribbon使用的负载均衡策略
  MaxAutoRetries=1 #同一台实例最大重试次数,不包括首次调用
  MaxAutoRetriesNextServer=1  #重试负载均衡其他的实例最大重试次数,不包括首次调用
  OkToRetryOnAllOperations=false  #是否所有操作都重试
  ServerListRefreshInterval=20000 #调整刷新server list的时间间隔
  api.mplus.distspace.com.ribbon.listOfServers=localhost:8080,localhost:8081  #服务器列表,可以通过静态的配置确定负载的服务器,也可以动态指定服务器列表,如果动态指定服务器列表,则会有后台线程来刷新该列表

The default ReadTimeout time 5s, ConnectTimeout time of 2s. Inter-service call with Fegin, with the bottom or the Ribbon


Reference article:

https://blog.csdn.net/u010862794/article/details/73649616

https://www.jianshu.com/p/8bca50cb11d8

Guess you like

Origin blog.csdn.net/wrs120/article/details/90691388
Recommended