In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to solve the common pits of custom feignClient". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to solve the common pits of custom feignClient".
Catalogue
Common pits for customizing feignClient
1. Pull the configuration information of relevant services from the eureka
2. FeignClient sends a request to the target server
III. Some pits
4. the following is all the existing code. Paste it out and have a look.
The use of feignClient
Service provider code
Service invoker
Common pits for customizing feignClient
Custom feignClient stepped on the pit, because spring cloud requires a version of spring 4 or above, so for the lower version of the project to use feign needs customization, in the definition process encountered a lot of problems, collation and summary. (if you need to combine github, please take your time. It's really handwritten, but some things can't be pasted out. Sorry, all the code is in the fourth point.)
The overall process is divided into two parts:
1. Pull the service address from eureka
2. FeignClient sends a request to the target server (in fact, feignClient ultimately uses httpClient to send a rest request, which is why the official website gives httpclient and feign-okhttp. Here, okthhp is used to support path requests).
1. Pull the configuration information of relevant services from the eureka
The default configuration for loading eureka is used here, and a singleton is used for initialization. The code is as follows
The purpose of 1pc2 is to load the configuration in the project, and the constants are defined as follows
Private static final String CLIENT_CONFIG_FILE_NAME = "eureka"; private static final String CLIENT_RIBBON_CONFIG_FILE_NAME = "ribbon"
Two files are defined under resource: eureka.properties and ribbon.properties (the name can be changed), which declares the necessary configuration of the service. The specific configuration is as follows:
Ribbon.properties
Aa.ribbon.DeploymentContextBasedVipAddresses=aa / / aa is the service name aa.ribbon.NIWSServerListClassName=com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList / / service invocation policy used in feign Polling and other aa.ribbon.ServerListRefreshInterval=60000 / / clients request eureka to refresh aa service node list time ribbon.ConnectTimeout=50000000 / / Service timeout ribbon.ReadTimeout=50000000eureka.propertieseureka.registration.enabled=false / / whether the service is registered to the eureka eureka.serviceUrl.default= http://discovery.ingageapp.com:9401/eureka / / eureka address # eureka.preferSameZone=true (the rest can not be enumerated # eureka.shouldUseDns=false with too many cans parameters under Baidu
The specific code is as follows. Take a look at the specific explanation of the code:
1 shi 2 two steps: loading ribbon and eureka configuration respectively
(3) load configuration information through DiscoveryManager.
Private XsyServiceLocator () {try {ConfigurationManager.loadCascadedPropertiesFromResources (CLIENT_RIBBON_CONFIG_FILE_NAME); / / 1 ConfigurationManager.loadCascadedPropertiesFromResources (CLIENT_CONFIG_FILE_NAME); / / 2} catch (IOException e) {throw new IllegalStateException ("Xsy client config load error! Please check your client.properties");} DiscoveryManager.getInstance (). InitComponent (new MyDataCenterInstanceConfig (), new DefaultEurekaClientConfig ()); / / 3} II, feignClient sends a request to the target server
1 FeignClient 2 two steps is to customize a @ FeignClient annotation, through the passed class to get the requested service name, that is, serviceId (if you can't do this, I can't help it, it's a little embarrassing)
3 Feign.builder () .client (new RibbonClient (new OkhttpClient () (in fact, the load balancer of feign sends requests through ribbon)
Here is the initialization of ribbonClient, and the final restclient uses okhttpclient.
4Jing 5 is used to encode and decode (don't use the pit with goson)
6 is used to record log about log, feign prints this at the debug level by default because he writes dead in the code that can rewrite feign's Slf4jLogger class changes.
7 is to set the log level (for which level to print something, search it yourself)
8 FeignInterceptor is to pass some request header downwards (you can rewrite the RequestInterceptor interface)
9 stitching parameters send information after stitching the request is "http://aa( service name) / info (finally, it will be spliced into the corresponding ip+ port number according to the service name on eureka, which is implemented by himself)
Public T lookup (Class clazz) {FeignClient feignClient = clazz.getAnnotation (FeignClient.class); / / 1 String serviceId = feignClient.value () / / 2 T service = Feign.builder () .client (new RibbonClient (new OkhttpClient () / / 3.encoder (new JacksonEncoder) / / 4.decoder (new JacksonDecoder) / / 5.logger (logger) / / 6.logLevel (Logger.Level.HEADERS) / / 7.requestInterceptor (new FeignInterceptor ()) / / 8 .target (clazz) "http://" + serviceId) / / 9 return service;} III. Some pits
1. Source code pit, during the implementation process, it is found that the configuration of ribbon does not take effect, because the feign-core source code problem, he will always new a config and then upload it, so you have to configure is invalid, rewrite here (the whole ribbonClient package copy down to change and then reference your own)
2 there seems to be a problem with this class (forgot)
4. Paste out all the existing code and take a look at public class XsyServiceLocator {private static final String CLIENT_CONFIG_FILE_NAME = "eureka"; private static final Object synRoot = new Object (); private static final String CLIENT_CONFIG_CUSTOM_FILED_NAME = "eureka.name"; private static final String CLIENT_RIBBON_CONFIG_FILE_NAME = "ribbon"; private static final JacksonEncoder jacksonEncoder = new JacksonEncoder (); private static final JacksonDecoder jacksonDecoder = new JacksonDecoder () Private static final RibbonClient ribbonClient = new RibbonClient (new OkHttpClient ()); private static String ipAddress = null; private static boolean isLoadEureka = true;// indicates that the default eureka configuration file needs to be loaded for true. If crm,false, load a custom eureka configuration file such as paas-aggregator-service private static XsyFeignLogger logger = null; private XsyServiceLocator () {try {ConfigurationManager.loadCascadedPropertiesFromResources (CLIENT_RIBBON_CONFIG_FILE_NAME). ConfigurationManager.loadCascadedPropertiesFromResources (CLIENT_CONFIG_FILE_NAME); Object eurekaName = ConfigurationManager.getConfigInstance (). GetProperty (CLIENT_CONFIG_CUSTOM_FILED_NAME); if (eurekaName! = null) {isLoadEureka = false;}} catch (IOException e) {throw new IllegalStateException ("Xsy client config load error!! Please check your client.properties ");} while (isLoadEureka & & ipAddress = = null) {DiscoveryManager.getInstance () .initComponent (new MyDataCenterInstanceConfig (), new DefaultEurekaClientConfig ()); ipAddress = DiscoveryManager.getInstance () .getEurekaInstanceConfig () .getIpAddress () }} public T lookup (Class clazz) {if (isLoadEureka & & ipAddress = = null) {DiscoveryManager.getInstance (). InitComponent (new MyDataCenterInstanceConfig (), new DefaultEurekaClientConfig ()); ipAddress = DiscoveryManager.getInstance (). GetEurekaInstanceConfig (). GetIpAddress ();} FeignClient feignClient = clazz.getAnnotation (FeignClient.class); String serviceId = feignClient.value () If (logger = = null) {synchronized (synRoot) {if (logger = = null) {logger = new XsyFeignLogger (clazz) T service = Feign.builder () .client (ribbonClient) .encoder (jacksonEncoder) .decoder (jacksonDecoder) .logger (logger) .logLevel (Logger.Level.HEADERS) .requestInterceptor (new FeignInterceptor ()) .targ et (clazz) "http://" + serviceId) Return service } feignClient user service provider code @ FeignClient (contextId = "remoteUserService", value = ServiceNameConstants.UPMS_SERVICE) public interface RemoteUserService {/ * query user name and role information by user name * * @ param username user name * @ param from call flag * @ return R * / @ GetMapping ("/ user/info/ {username}") R info (@ PathVariable ("username") String username, @ RequestHeader (SecurityConstants.FROM) String from) } @ GetMapping ("/ user/info/ {username}") is the one in the service Controller package (@ Inner annotation represents the internal method, which is called directly without permission Will not be blocked by network management) / * get all the information of the specified user * * @ return user information * / @ Inner @ GetMapping ("/ info/ {username}") public R info (@ PathVariable String username) {SysUser user = userService.getOne (Wrappers.query () .lambda () .eq (SysUser::getUsername, username)) If (user = = null) {return R.failed (null, String.format ("user information is empty% s", username));} return R.ok (userService.findUserInfo (user));} service caller
(SecurityConstants.FROM_IN is an identification value of IN for service calls within the system.)
@ Slf4j@AllArgsConstructorpublic class HzUserDetailsServiceImpl implements HzUserDetailsService {private final RemoteUserService remoteUserService; private final CacheManager cacheManager; / * user password login * * @ param username user name * @ return * @ throws UsernameNotFoundException * / @ Override @ SneakyThrows public UserDetails loadUserByUsername (String username) {Cache cache = cacheManager.getCache (CacheConstants.USER_DETAILS); if (cache! = null & & cache.get (username)! = null) {return (HzUser) cache.get (username) .get () } R result = remoteUserService.info (username, SecurityConstants.FROM_IN); UserDetails userDetails = getUserDetails (result); cache.put (username, userDetails); return userDetails;}} Thank you for reading, the above is the content of "how to solve the common pits of custom feignClient". After the study of this article, I believe you have a deeper understanding of how to solve the common pits of custom feignClient, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.