SpringBoot actual electricity supplier item mall (20k + star) Address: github.com/macrozheng/...
Summary
Spring Cloud OpenFeign service call is declarative tool that integrates Ribbon and Hystrix, have load balancing and fault tolerance service, we will detail its usage.
Feign Profile
Feign service call is declarative tools, we only need to create an interface with annotations and ways to configure it, you can achieve a call to a service interface, simplifying the development of direct use to call RestTemplate amount of service interfaces. Feign with pluggable annotation support, while supporting Feign annotations, JAX-RS annotations and SpringMvc comment. When using Feign, Spring Cloud integrates Ribbon and Eureka to provide load balancing service calls and service-based Hystrix fault tolerance protection.
Create a feign-service module
Here we create a feign-service module to demonstrate the common features feign.
Add its dependencies in pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
复制代码
In the configuration application.yml
server:
port: 8701
spring:
application:
name: feign-service
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8001/eureka/
复制代码
Add @EnableFeignClients comment on the start of classes to enable Feign client functionality
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class FeignServiceApplication {
public static void main(String[] args) {
SpringApplication.run(FeignServiceApplication.class, args);
}
}
复制代码
Add UserService interface to complete the interface is bound to user-service services
We implemented a Feign client by @FeignClient notes, the value of which is user-service interface calls that this is a client of the user-service services. We can recall at user-service in UserController, simply change it to interface to retain the original SpringMvc comment.
/**
* Created by macro on 2019/9/5.
*/
@FeignClient(value = "user-service")
public interface UserService {
@PostMapping("/user/create")
CommonResult create(@RequestBody User user);
@GetMapping("/user/{id}")
CommonResult<User> getUser(@PathVariable Long id);
@GetMapping("/user/getByUsername")
CommonResult<User> getByUsername(@RequestParam String username);
@PostMapping("/user/update")
CommonResult update(@RequestBody User user);
@PostMapping("/user/delete/{id}")
CommonResult delete(@PathVariable Long id);
}
复制代码
Add UserFeignController call UserService achieve service call
/**
* Created by macro on 2019/8/29.
*/
@RestController
@RequestMapping("/user")
public class UserFeignController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public CommonResult getUser(@PathVariable Long id) {
return userService.getUser(id);
}
@GetMapping("/getByUsername")
public CommonResult getByUsername(@RequestParam String username) {
return userService.getByUsername(username);
}
@PostMapping("/create")
public CommonResult create(@RequestBody User user) {
return userService.create(user);
}
@PostMapping("/update")
public CommonResult update(@RequestBody User user) {
return userService.update(user);
}
@PostMapping("/delete/{id}")
public CommonResult delete(@PathVariable Long id) {
return userService.delete(id);
}
}
复制代码
Load balancing feature presentation
- Start eureka-service, two user-service, feign-service service, after starting the registry is shown below:
- Multiple calls to http: // localhost: 8701 / user / 1 test run can be found alternately print the following information in 8201 and 8202 of the user-service service:
2019-10-04 15:15:34.829 INFO 9236 --- [nio-8201-exec-5] c.macro.cloud.controller.UserController : 根据id获取用户信息,用户名称为:macro
2019-10-04 15:15:35.492 INFO 9236 --- [io-8201-exec-10] c.macro.cloud.controller.UserController : 根据id获取用户信息,用户名称为:macro
2019-10-04 15:15:35.825 INFO 9236 --- [nio-8201-exec-9] c.macro.cloud.controller.UserController : 根据id获取用户信息,用户名称为:macro
复制代码
Feign in service degradation
Feign in service degradation is easy to use, only need to add the interfaces as defined by the client Feign a class can implement downgrade service, let's implement a class for the service degradation UserService add an interface.
Add Service downgraded implementation class UserFallbackService
Note that it implements the UserService interfaces, and each interface implemented method were implemented logic service degradation.
/**
* Created by macro on 2019/9/5.
*/
@Component
public class UserFallbackService implements UserService {
@Override
public CommonResult create(User user) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
}
@Override
public CommonResult<User> getUser(Long id) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
}
@Override
public CommonResult<User> getByUsername(String username) {
User defaultUser = new User(-1L, "defaultUser", "123456");
return new CommonResult<>(defaultUser);
}
@Override
public CommonResult update(User user) {
return new CommonResult("调用失败,服务被降级",500);
}
@Override
public CommonResult delete(Long id) {
return new CommonResult("调用失败,服务被降级",500);
}
}
复制代码
UserService modify the interface, arranged to downgrade the service class UserFallbackService
Modify the parameters @FeignClient annotations, and can set fallback to UserFallbackService.class.
@FeignClient(value = "user-service",fallback = UserFallbackService.class)
public interface UserService {
}
复制代码
Modify application.yml, open Hystrix function
feign:
hystrix:
enabled: true #在Feign中开启Hystrix
复制代码
Service downgraded Demo
-
Close both user-service service, restart feign-service;
-
Call http: // localhost: 8701 / user / 1 for testing can be found returned service degradation information.
Log Print function
Feign provides a log printing capabilities, we can adjust the log level by configuring to understand the details of Feign in Http request.
Log Level
- NONE: default, does not show any log;
- BASIC: Only requests recording method, URL, and the response status code execution time;
- HEADERS: BASIC addition to the information defined in the header information as well as request and response;
- FULL: HEADERS defined in addition to the information, as well as text and metadata requests and responses.
Open a more detailed log by configuring
Let's Feign print the java configuration is the most detailed Http request log information.
/**
* Created by macro on 2019/9/5.
*/
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
复制代码
In application.yml need to open Feign configure client log
UserService configuration of log level debug.
logging:
level:
com.macro.cloud.service.UserService: debug
复制代码
View Log
Call http: // localhost: 8701 / user / 1 for testing, you can see the following log.
2019-10-04 15:44:03.248 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] ---> GET http://user-service/user/1 HTTP/1.1
2019-10-04 15:44:03.248 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] ---> END HTTP (0-byte body)
2019-10-04 15:44:03.257 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] <--- HTTP/1.1 200 (9ms)
2019-10-04 15:44:03.257 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] content-type: application/json;charset=UTF-8
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] date: Fri, 04 Oct 2019 07:44:03 GMT
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] transfer-encoding: chunked
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser]
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] {"data":{"id":1,"username":"macro","password":"123456"},"message":"操作成功","code":200}
2019-10-04 15:44:03.258 DEBUG 5204 --- [-user-service-2] com.macro.cloud.service.UserService : [UserService#getUser] <--- END HTTP (92-byte body)
复制代码
Feign common configuration
Feign own configuration
feign:
hystrix:
enabled: true #在Feign中开启Hystrix
compression:
request:
enabled: false #是否对请求进行GZIP压缩
mime-types: text/xml,application/xml,application/json #指定压缩的请求数据类型
min-request-size: 2048 #超过该大小的请求会被压缩
response:
enabled: false #是否对响应进行GZIP压缩
logging:
level: #修改日志级别
com.macro.cloud.service.UserService: debug
复制代码
Ribbon in the configuration Feign
Feign configuration can be used directly in the Ribbon Ribbon configuration, specifically refer to Spring Cloud Ribbon: load balancing service call .
Hystrix configuration of Feign
Feign configuration can be used directly in Hystrix Hystrix configuration, specifically refer to Spring Cloud Hystrix: Service fault tolerance protection .
To use the module
springcloud-learning
├── eureka-server -- eureka注册中心
├── user-service -- 提供User对象CRUD接口的服务
└── feign-service -- feign服务调用测试服务
复制代码
Project Source Address
No public
mall project a full tutorial serialized in public concern number the first time to obtain.