This article mainly introduces the method of learning springboot to integrate feign cross-service calls from scratch. This article introduces you in very detail, which has a certain reference value for everyone's study or work. Friends who need it can refer to
In the Internet world where microservices are rampant, cross-service calls seem very ordinary. In addition to using traditional http interface calls, is there a more elegant and convenient method?
The answer is yes, feign provides a light way!
If your services are registered with a registry, such as nacos, then the call will be very easy, just an annotation, bring the name of the service that needs to be called, and feign + nacos will help you do the rest.
If there is no registration center, there is no need to worry, feign can use the traditional
ip:port
Way to call~
Next, let's practice it
Springboot integrates feign to
introduce dependencies. Note here that spring-cloud.version must match the spring-boot version. My spring-boot version is 2.1.3, so spring-cloud chooses the Greenwich.SR2 version.
The approximate version correspondence is as follows
For more details, please go to https://start.spring.io/actuator/info for
inquiries!
<properties>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties>
<dependencyManagement>
<dependencies>
<!--SpringCloud依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${
spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!--openfeign跨服务调用-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--openfeign底层使用ApacheHttpClient调用-->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
</dependencies>
Then we go to the startup class of the project and add an annotation
Finally, add Feign configuration
server.port=9999
#******************openfeign配置,参数采用的是默认的配置,可根据实际情况调整***********************
#启用ApacheHttpClient。默认就是true,使用HttpClientConnectionManager管理连接复用
feign.httpclient.enabled=true
#连接池的最大连接数,默认200
feign.httpclient.max-connections=200
#每个路由(服务器)分配的组最大连接数,默认50
feign.httpclient.max-connections-per-route=50
#连接最大存活时间,默认900秒
feign.httpclient.time-to-live=900
#连接最大存活时间单位秒
feign.httpclient.time-to-live-unit=seconds
#FeignAcceptGzipEncodingInterceptor拦截器被激活,会在header中添加Accept-Encoding:gzip,deflate,表明服务端在返回值时可以使用如下两个方式压缩返回结果
feign.compression.response.enabled=true
#FeignContentGzipEncodingInterceptor拦截器被激活,会在header中添加Content-Encoding:gzip,deflate,表明body中的参数是使用这两个方式的压缩
feign.compression.request.enabled=true
#content-length大于2048就进行请求参数的gzip压缩
feign.compression.request.minRequestSize=2048
#开启断路器
feign.hystrix.enabled=true
#断路器的隔离策略,默认就是线程池,SEMAPHORE模式下,就是主线程调用的远程的服务,即同步的
hystrix.command.default.execution.isolation.strategy=THREAD
#断路器超时设置
hystrix.command.default.execution.timeout.enabled=true
#总体请求在45秒还是无法得到响应,建议触发熔断(ribbon每个请求读取15秒超时,两个实例重试就是30秒,openfeign外层默认会进行一次调用,4次重试)
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=45000
#断路器的线程池存在一个问题,在队列满了以后,不会再去创建新的线程直到maximumSize
#核心线程池大小
hystrix.threadpool.default.coreSize=10
#最大线程池大小
hystrix.threadpool.default.maximumSize=10
#超过这个空闲时间,多于coreSize数量的线程会被回收,1分钟
hystrix.threadpool.default.keepAliveTimeMinutes=1
#队列的大小,默认为-1,即没有队列
hystrix.threadpool.default.maxQueueSize=200
#队列任务达到此阈值后,就开始拒绝;实际使用此参数进行队列是否满的判断
hystrix.threadpool.default.queueSizeRejectionThreshold=180
#负载均衡配置
#读取超时15秒,与原RestTemplate保持一致
ribbon.ReadTimeout=15000
#连接超时15秒,与原RestTemplate保持一致
ribbon.ConnectTimeout=15000
##每台服务器最多重试次数,但是首次调用不包括在内
ribbon.MaxAutoRetries=0
##最多重试多少台服务器,与实际实例数保持一致(不包括首台)
ribbon.MaxAutoRetriesNextServer=1
#是否所有操作都重试,
# false:get请求中,连接超时,读取超时都会重试,其他请求(put,post)连接超时重试,读取超时不重试。
# true:get请求中,连接超时,读取超时都会重试,其他请求(put,post)连接超时重试,读取超时重试。
#对于请求(put,post)要做好接口的幂等性
ribbon.OkToRetryOnAllOperations=true
spring-boot整合feign完成, 接下来我们编写测试代码
Test code
two services
- sb-alibaba-nacos (callee service, 127.0.0.1:8081), provides getInfoById interface
- sb-feign (caller service, 127.0.0.1:9999), provide getInfoById test interface
- Test interface provided by sb-alibaba-nacos
@GetMapping(value = "getInfoById")
public String getInfoById(@RequestParam(value = "id") Long Id) {
return "example-service return :" + Id;
}
For sb-feign related code,
we create a new package feign to put all classes involving cross-service calls
ExampleControllerFeignClient.java:
`package` `com.mrcoder.sbfeign.feign;`
`import` `feign.hystrix.FallbackFactory;`
`import` `org.slf4j.Logger;`
`import` `org.slf4j.LoggerFactory;`
`import` `org.springframework.cloud.openfeign.FeignClient;`
`import` `org.springframework.stereotype.Component;`
`import` `org.springframework.web.bind.annotation.GetMapping;`
`import` `org.springframework.web.bind.annotation.RequestParam;`
`@FeignClient``(name =` `"sb-alibaba-nacos"``, url =` `"[http://127.0.0.1:8081/](http://127.0.0.1:8081/)"``, fallbackFactory = ExampleControllerFeignClient.ExampleControllerFeignClientFallbackFactory.``class``)`
`public` `interface` `ExampleControllerFeignClient {
`
`@GetMapping``(value =` `"getInfoById"``)`
`String getInfoById(``@RequestParam``(value =` `"id"``) Long Id);`
`/**`
`* 服务降级内部类`
`*/`
`@Component`
`class` `ExampleControllerFeignClientFallbackFactory` `implements` `FallbackFactory<ExampleControllerFeignClient> {
`
`private` `Logger logger = LoggerFactory.getLogger(ExampleControllerFeignClientFallbackFactory.``class``);`
`@Override`
`public` `ExampleControllerFeignClient create(Throwable cause) {
`
`return` `new` `ExampleControllerFeignClient() {
`
`@Override`
`public` `String getInfoById(Long signingLogId) {
`
`logger.error(``"跨服务调用失败, 原因是:"` `+ cause.getMessage());`
`return` `"失败, 原因是:"` `+ cause.getMessage();`
`}`
`};`
`}`
`}`
`}`
The key code is
`@FeignClient``(name =` `"sb-alibaba-nacos"``, url =` `"[http://127.0.0.1:8081/](http://127.0.0.1:8081/)"``, fallbackFactory = ExampleControllerFeignClient.ExampleControllerFeignClientFallbackFactory.``class``)`
- name is the service name of the callee (if you have not configured the service registry, you can write it casually)
- url is the address of the callee (if the service registration center is configured, it can be omitted!, but both services must be registered!, so that you can find it!)
- fallbackFactory is the processing class specified when the call fails.
Finally, we write a test method
package com.mrcoder.sbfeign.controller;
import com.mrcoder.sbfeign.feign.ExampleControllerFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@CrossOrigin
@RestController
public class TestController {
@Autowired
private ExampleControllerFeignClient exampleControllerFeignClient;
@RequestMapping(value = "getInfoById", method = RequestMethod.GET)
public String test(@RequestParam(value = "id") Long Id) {
return exampleControllerFeignClient.getInfoById(Id);
}
}
Open two services sb-alibaba-nacos, sb-feign
Then visit the test method of sb-feign
http://localhost:9999/getInfoById?id=22
appear
sb-alibaba-nacos return :22
Successful cross-service call~
So far, this article about learning springboot to integrate feign cross-service calls from scratch is introduced. For more related springboot integration feign cross-service calls, please follow the editor or add QQ1411943564 to receive