当前位置:网站首页>Openfeign use step polling strategy and weight log4j configuration of openfeign interceptor
Openfeign use step polling strategy and weight log4j configuration of openfeign interceptor
2022-06-29 17:27:00 【kjshuan】
Call component Feign(openFeign)
JAVA How to implement interface call in project ? 1)Httpclient HttpClient yes Apache Jakarta Common Sub projects under , To provide efficient 、 Abreast of the times 、 Rich in functions Support for Http Client programming toolkit for protocol , And it supports HTTP The latest version of the agreement and recommendations .HttpClient Compared with tradition JDK Self contained URLConnection, Improved ease of use and flexibility , Make the client send HTTP It's easier to ask , Improved development efficiency . 2)Okhttp An open source project to handle network requests , It's the most popular lightweight framework in Android , from Square The company contributed , Used in substitution HttpUrlConnection and Apache HttpClient.OkHttp Have a simple API、 Efficient performance , And support a variety of protocols (HTTP/2 and SPDY). 3)HttpURLConnection HttpURLConnection yes Java Standard class , It is inherited from URLConnection, Can be used to send GET request 、POST request .HttpURLConnection It's complicated to use , Unlike HttpClient That's easy to use . 4)RestTemplate WebClient RestTemplate yes Spring Provided for access Rest Client of service ,RestTemplate Provides a variety of convenient remote access HTTP Method of service , Can greatly improve the writing efficiency of the client . The above are the most common methods to call the interface , The method we're going to introduce next is simpler than the one above 、 convenient , It is Feign.
What Well yes Feign ( This is especially for openFeign)
1.Feign yes Netflix Developed declarative 、 templated HTTP client , It's inspired by Retrofit、JAXRS-2.0 as well as WebSocket.Feign Can help us more convenient 、 Call... Gracefully HTTP API. Feign Support multiple annotations , for example Feign Own notes or JAX-RS Annotations etc. . #!!!!!!!!!!!!!!!!!!!!! Spring Cloud openfeign Yes Feign Enhanced , To support Spring MVC annotation , In addition, it integrates Ribbon and Nacos, Thus making Feign It is more convenient to use advantage Feign It can be used HTTP When requesting a remote service, it's like calling a local method , Developers don't realize it's a remote method , I don't even know it's a HTTP request . It looks like Dubbo equally ,consumer Directly call the interface method provider, It doesn't have to go through the regular Http Client Construct the request and parse the returned data . It solves the problem of allowing developers to call remote interfaces just like calling local methods , No need to pay attention to the details of the interaction with the remote , Let alone focus on distribution Open environment development .
How do you use it? ?
linux Direct start nacos # start-up startup.sh # Open the browser 192.168.64.200:8848/nacos/#/login# Enter the address to execute the order Inventory deduction http://localhost:12002/order-server/addorder
Use steps
First step Introduce dependencies
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
Two steps Write call interface [email protected] annotation
@FeignClient(value = "stockserv",path = "/stock-server")
public interface StockFeignService {
@RequestMapping("/reduced")
public String reduced();
}
The third step The caller adds... On the startup class @EnableFeignClients annotation
@SpringBootApplication
@EnableFeignClients
public class OrderFeignApplication {
public static void main(String[] args) {
SpringApplication.run(OrderFeignApplication.class,args);
}
}
Step four A call , Call the remote service as if it were local
@RestController
@RequestMapping("/order-server")
public class OrderCtrl {
@Resource
private StockFeignService stockFeignService;
@Value("${dev.stock.baseurl}")
private String baseUrl;
@Value("${dev.stock.module.apiaddr[0]}")
private String reduceStock;
@GetMapping("/addorder")
public String adds(){
return " Add order 111111111,"+stockFeignService.reduced();
}
}After configuring the self-contained polling ( Line up one by one )
If you want to take the weight as follows 4 Ways of planting
among application in 2 Kind of
###application Class
## To configure application
@SpringBootApplication
@EnableFeignClients
//@RibbonClients(value={
// @RibbonClient(name="stockserv",configuration= RibbonRule.class)
//})
public class OrderFeignApplication {
public static void main(String[] args) {
SpringApplication.run(OrderFeignApplication.class,args);
}
}
## To configure rules The weight of a class system
@Configuration
public class RibbonRule {
// Manual weights
@Bean
public IRule iRule(){
// return new NacosRule();
// Auto weight
return new RandomRule();
}
}
###application Class
## To configure application
@SpringBootApplication
@EnableFeignClients
//@RibbonClients(value={
// @RibbonClient(name="stockserv",configuration= MyNacosRule.class)
//})
public class OrderFeignApplication {
public static void main(String[] args) {
SpringApplication.run(OrderFeignApplication.class,args);
}
}
## To configure rules Class custom weights
public class MyNacosRule extends AbstractLoadBalancerRule {
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Override
public Server choose(Object o) {
// Get a list of dynamic services from the registry
DynamicServerListLoadBalancer lb= (DynamicServerListLoadBalancer)getLoadBalancer();
// Get service name
String serverName = lb.getName();
// Build service name instance
NamingService ns = nacosDiscoveryProperties.namingServiceInstance();
//nacos Weight based algorithm
try {
Instance instance = ns.selectOneHealthyInstance(serverName);
// Put it into the server
return new NacosServer(instance);
} catch (NacosException e) {
e.printStackTrace();
}
// If something goes wrong Then return the user null
return null;
}
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
}yum One species
# To configure yum
stockserv:
ribbon:
NFLoadBalancerRuleClassName: com.kgc.rrules.MyNacosRule
## To configure rules Class custom weights
public class MyNacosRule extends AbstractLoadBalancerRule {
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Override
public Server choose(Object o) {
// Get a list of dynamic services from the registry
DynamicServerListLoadBalancer lb= (DynamicServerListLoadBalancer)getLoadBalancer();
// Get service name
String serverName = lb.getName();
// Build service name instance
NamingService ns = nacosDiscoveryProperties.namingServiceInstance();
//nacos Weight based algorithm
try {
Instance instance = ns.selectOneHealthyInstance(serverName);
// Put it into the server
return new NacosServer(instance);
} catch (NacosException e) {
e.printStackTrace();
}
// If something goes wrong Then return the user null
return null;
}
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
}
log4j Use
debug--> Debugging use info--> In general use warn--> error-->
The first one is Configure the log class
@Configuration
// Configure the log class
public class LogConf {
@Bean
public Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
The second kind To configure yum file
logging: level: com.kgc.mynacos.orderfeignserv.remoteserv: debug feign: client: config: stockserv: loggerLevel: Full1feign: 2client: 3config: 4mall‐order: # Corresponding to microservices 5loggerLevel: FULL 6contract: feign.Contract.Default # Appoint Feign Native annotation contract configuration

Custom interceptors implement authentication logic
First step
@Configuration
// Configure the log class Interceptor
public class LogConf {
// @Bean
// public Logger.Level feignLoggerLevel(){
// return Logger.Level.FULL;
// }
@Bean
public AddTokenInterceptor addTokenInterceptor(){
return new AddTokenInterceptor();
}
}
The second step
# Configure interceptor entity class inheritance openfign Built in interceptor requests
public class AddTokenInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
// The consumer is requesting Add an acquired... To the header of the post service TOKEN
String token = UUID.randomUUID().toString();
System.out.println(" The consumer interceptor starts , Add... To the head token:"+token);
requestTemplate.header("token",token);
}
}The third step
# To configure yum server: port: 12002 spring: application: name: orderfeginserv cloud: nacos: discovery: server-addr: 192.168.64.200:8848 username: nacos password: nacos namespace: public #dev: # stock: # baseurl: http://stockserv/ # module: # apiaddr: # - /stock-server/reduced stockserv: ribbon: NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule #logging: # level: # com.kgc.mynacos.orderfeignserv.remoteserv: debug #feign: # client: # config: # stockserv: # loggerLevel: Full #----------------------------------------- The following is a must feign: client: config: orderfeignserv: requestInterceptors: - com.kgc.mynacos.orderser.interceptor.AddTokenInterceptor
# Launch the browser
http://localhost:12002/order-server/addorder
Request header : Generally put the calibration parameters cookie Please go the way state Address
Why? nginx Adopt multi process structure instead of multi thread structure ?
nginx Purpose : Maintain high availability and reliability . If you use the multithreading model , Shared address space between threads , If a third-party module causes a segment error caused by the address space , When the address appears out of bounds , Will lead to the whole nginx All hang up . This problem does not occur with multiple processes .Nginx Server load balancing strategies can be divided into two categories : Built in policy and extended policy . The built-in policy mainly includes polling 、 Weighted polling and IP hash Three ; The extension strategy is mainly implemented through third-party modules , There are many kinds of them , Common are url hash、fair etc. .
边栏推荐
- 关于Go中两个模块互相调用的场景解决方案
- Online sql to CSV tool
- 如何创建虚拟形象
- 2022 software evaluator examination outline
- Viewing splitchunks code segmentation from MPX resource construction optimization
- NVIDIA安装最新显卡驱动
- 自学结构体(小甲鱼c语言)
- windows平台下的mysql启动等基本操作
- Subgraphs in slam
- ICML 2022 | transferable imitation learning method based on decoupling gradient optimization
猜你喜欢

Shenzhen internal promotion | Shenzhen Institute of computing science recruits assistant machine learning Engineer (school recruitment)

How to create and delete MySQL triggers

Word2vec vector model of Wiki Chinese corpus based on deep learning

Automatic vending machine

How MySQL queries character set codes of tables

底层内功修养

mysql在linux中2003错误如何解决

controller、service、dao之间的关系

【R语言数据科学】:文本挖掘(以特朗普推文数据为例)

0基础自学STM32(野火)——寄存器点亮LED
随机推荐
KUKA子程序/函数怎么建立和使用方法
PCB frame drawing - ad19
自学结构体(小甲鱼c语言)
Mysql中锁的使用场景是什么
L'intercepteur handlerinterceptor personnalisé permet l'authentification de l'utilisateur
mysql游标的作用是什么
ICML 2022 | transferable imitation learning method based on decoupling gradient optimization
Multi mode concurrent implementation of tortoise and rabbit race in go language
Use SSH to pull codes
About harbor private warehouse forgetting the login password
基于深度学习的Wiki中文语料词word2vec向量模型
Development of freedom free agreement pledge mining system
KUKA robot external axis configuration what you must know
Why is informatization ≠ digitalization? Finally someone made it clear
基于汇编实现的流载体的LSB隐藏项目
mysql. What is the concept of sock
0基础自学STM32(野火)——寄存器点亮LED
自定義HandlerInterceptor攔截器實現用戶鑒權
反射
函数计算异步任务能力介绍 - 任务触发去重