In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you the relevant knowledge about the method of SpringCloud Feign Jackson custom configuration. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Feign Jackson Custom configuration
Spring Cloud Feign supports Spring MVC annotations using the same HttpMessageConverters class transformation by default
The official document states:
Spring Cloud adds support for Spring MVC annotations and for using the same HttpMessageConverters used by default in Spring Web.
But we usually change the corresponding NULL value to the corresponding "" when returning to the front-end JSON format, which makes Spring Cloud Feign use the same Jackson configuration, such as the configuration of our project.
@ Bean public ObjectMapper jacksonObjectMapper () {ObjectMapper objectMapper = new ObjectMapper (); / / objectMapper.setSerializationInclusion (Include.NON_NULL); objectMapper.getSerializerProvider () .setNullValueSerializer (new JsonSerializer () {@ Override public void serialize (Object value, JsonGenerator jg, SerializerProvider sp) throws IOException, JsonProcessingException {jg.writeString ("); sp.getDefaultNullKeySerializer () Problems with objectMapper.configure (SerializationFeature.FAIL_ON_EMPTY_BEANS, false); return objectMapper;}
When the service makes a request through Feign, a type conversion exception occurs when the NULL value is passed to refer to the type value, because HttpMessageConverters directly converts the NULL to "".
Solution idea
Custom configuration of Spring Cloud Feign Encoder and Decoder
The official document states:
Spring Cloud Netflix provides the following beans by default for feign (BeanType beanName: ClassName): Decoder feignDecoder: ResponseEntityDecoder (which wraps a SpringDecoder) Encoder feignEncoder: SpringEncoderLogger feignLogger: Slf4jLoggerContract feignContract: SpringMvcContractFeign.Builder feignBuilder: HystrixFeign.BuilderClient feignClient: if Ribbon is enabled it is a LoadBalancerFeignClient, otherwise the default feign client is used.
Solution method
Unified configuration of Encoder of Feign and Jackson conversion of Decoder
Import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.beans.factory.ObjectFactory;import org.springframework.boot.autoconfigure.http.HttpMessageConverters;import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;import org.springframework.cloud.openfeign.support.SpringDecoder;import org.springframework.cloud.openfeign.support.SpringEncoder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.http.converter.HttpMessageConverter;import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter Import feign.codec.Decoder;import feign.codec.Encoder;@Configurationpublic class CustomFeignConfig {@ Bean public Decoder feignDecoder () {HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter (customObjectMapper ()); ObjectFactory objectFactory = ()-> new HttpMessageConverters (jacksonConverter); return new ResponseEntityDecoder (new SpringDecoder (objectFactory));} @ Bean public Encoder feignEncoder () {HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter (customObjectMapper ()); ObjectFactory objectFactory = ()-> new HttpMessageConverters (jacksonConverter) Return new SpringEncoder (objectFactory);} public ObjectMapper customObjectMapper () {ObjectMapper objectMapper = new ObjectMapper (); / / Customize as much as you want objectMapper.configure (DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true); return objectMapper;}}
If configuring DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT doesn't work, you can try this.
Public ObjectMapper customObjectMapper () {ObjectMapper objectMapper = new ObjectMapper (); / / Customize as much as you want objectMapper.registerModule (new StringSanitizerModule ()); return objectMapper;} public class StringSanitizerModule extends SimpleModule {public StringSanitizerModule () {addDeserializer (String.class, new StdScalarDeserializer (String.class) {@ Override public String deserialize (JsonParser jsonParser, DeserializationContext ctx) throws IOException {return StringUtils.trimToNull (jsonParser.getValueAsString ()) }});}} Feign custom configuration application environment
Nacos: 1.3.1
Start nacos
Cd / usr/local/nacos/bin
Sh startup.sh-m standalone
Customize the configuration of Feign
1) add dependencies
Add dependency of nacos-discovery Discovery Service, web, actuator for monitoring check, and add openfeign dependency to use Feign function.
2) modify the configuration file
Configure the nacos registry address, because no services are provided, so there is no need for registry registration, so register-enabled=false
3) add Feign support
Configure FeignConfiguration class files
The default SpringMvcController of Spring Cloud Netflix will be replaced with feign.Contract.Default
Using feign.Contract.Default to change the contract to the native default contract of Feign, you can use the annotations that come with feign.
4) Custom Feign API
The Feign interface file needs to be in the same package directory as the startup class. Use @ FeignClient annotation to configure the required services. Here, nacos-provider needs to provide services in the registry.
Because feign.Contract.Deafault is configured above, the native annotation @ RequestLine of Feign can be used in the interface
Add a HelloController class file
Here we use the interface MyFeignClient to call the hello method to get the services provided by the nacos-provider client
Log in Feign
1) add configuration item
Add logging packages to the configuration file, * and each FeignClient needs to be configured separately, which can only respond to debug-level logs
2) set log level
Configure log levels in the FeignConfiguration class file
Log level:
NONE: do not record (default)
BASIC: only the request method, URL, response status code and execution time are recorded
HEADERS: record basic information, request and response headers
FULL: record request and response headers, body, and row data
Test the configuration customized by Feign
Start the nacos-provider and feign-config clients, and enter nacos to query whether the nacos-provider service is registered
Enter the browser and type the address http://localhost:2334/hello to access the service content provided by nacos-provider.
View the log
The console will output the following information
[MyFeignClient#hello]
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.