[Special topic on Fegin technology] "Original ecology" opened the beginning of Fegin's RPC technology. Would you use the original ecology of Fegin? (Down)

brief introduction

In project development, in addition to considering normal calls, load balancing and failover are also the focus of attention. This is also the advantage of feign + ribbon. Based on the basis of the above two articles, we will launch the last original ecological fegin Combined with the ribbon service to make remote service calls and realize the load balancing mechanism, it also helps everyone to lay the foundation for learning ribbon.

maven dependencies

<dependencies>
    <dependency>
        <groupId>com.netflix.feigngroupId>
        <artifactId>feign-coreartifactId>
        <version>8.18.0version>
    dependency>
    <dependency>
        <groupId>com.netflix.feigngroupId>
        <artifactId>feign-jacksonartifactId>
        <version>8.18.0version>
    dependency>
    <dependency>
        <groupId>com.netflix.feigngroupId>
        <artifactId>feign-ribbonartifactId>
        <version>8.18.0version>
    dependency>
	<dependency>
    <groupId>com.netflix.archaiusgroupId>
    <artifactId>archaius-coreartifactId>
dependency>

dependencies>
复制代码

Among them, feign-core and feign-ribbon are necessary. If object interaction between the service consumer and the service producer is required, it is recommended to use feign-jackson

configuration read

import com.netflix.config.ConfigurationManager;
import feign.Feign;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.ribbon.RibbonClient;
public class AppRun {
    
    
    public static void main(String[] args) throws Exception {
    
    
        User param = new User();
        param.setUsername("test");
        RemoteService service = Feign.builder().client(RibbonClient.create())
				.encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder())
			    .options(new Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3))
			    .target(RemoteService.class, "http://remote-client/gradle-web");

        for (int i = 1; i 10; i++) {
    
    
            User result = service.getOwner(param);
            System.out.println(result.getId() + "," + result.getUsername());
        }
    }
}
复制代码
  • An object param of User type is declared, which will be sent to the service producer as a parameter.
  • The key point is to make the Feign object obtain the characteristics of Ribbon through RibbonClient.create(). Then set the encoder and decoder through encoder and decoder, and bind the previously defined interface RemoteService with a URL address http://remote-client/gradle-web through the target method .

Now look at the configuration items in remote-client.properties, mainly the configuration mechanism of RemoteClient

remote-client.ribbon.MaxAutoRetries=1
remote-client.ribbon.MaxAutoRetriesNextServer=1
remote-client.ribbon.OkToRetryOnAllOperations=true
remote-client.ribbon.ServerListRefreshInterval=2000
remote-client.ribbon.ConnectTimeout=3000
remote-client.ribbon.ReadTimeout=3000
remote-client.ribbon.listOfServers=127.0.0.1:8080,127.0.0.1:8085
remote-client.ribbon.EnablePrimeConnections=false
复制代码

All keys start with remote-client, indicating that these configuration items act on the service named remote-client. In fact, it corresponds to the schema of the URL address that was previously bound to the RemoteService interface.

Focus on the remote-client.ribbon.listOfServers configuration item, which specifies the real address of the service production end.

will be replaced by:

The address specified by @RequestLine is spliced ​​to get the final request address. In this example, the final request address is:

Due to the use of ribbon, feign no longer needs to configure the timeout period and retry strategy. Ribbon provides a more complete strategy implementation.

In this example, the service producer is a simple springMvc, which is implemented as follows:


public class UserController {
    
    

    public User list( User user) throws InterruptedException{
    
    
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        user.setId(new Long(request.getLocalPort()));
        user.setUsername(user.getUsername().toUpperCase());
        return user;
    }
}

复制代码

Failover is configured through configuration items in remote-client.properties.

  • First, use the com.netflix.config.ConfigurationManager of the archaius project to read the configuration file remote-client.properties, which is located under src/main/resources.

How to set the load balancing strategy?

import com.netflix.client.ClientFactory;
import com.netflix.client.config.IClientConfig;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.RandomRule;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import feign.Feign;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import feign.ribbon.LBClient;
import feign.ribbon.LBClientFactory;
import feign.ribbon.RibbonClient;
public class AppRun {
    
    
    public static void main(String[] args) throws Exception {
    
    
        ConfigurationManager.loadPropertiesFromResources("remote-client.properties");
        User param = new User();
        param.setUsername("test");
        RibbonClient client = RibbonClient.builder().lbClientFactory(new LBClientFactory() {
    
    

            public LBClient create(String clientName) {
    
    
                IClientConfig config = ClientFactory.getNamedConfig(clientName);
                ILoadBalancer lb = ClientFactory.getNamedLoadBalancer(clientName);
                ZoneAwareLoadBalancer zb = (ZoneAwareLoadBalancer) lb;
                zb.setRule(new RandomRule());
                return LBClient.create(lb, config);
            }
        }).build();
        RemoteService service = Feign.builder().client(client).encoder(new JacksonEncoder())
                .decoder(new JacksonDecoder()).options(new Options(1000, 3500))
                .retryer(new Retryer.Default(5000, 5000, 3)).target(RemoteService.class, "http://remote-client/gradle-web");

        for (int i = 1; i 10; i++) {
    
    
            User result = service.getOwner(param);
            System.out.println(result.getId() + "," + result.getUsername());
        }
    }
}
复制代码

	private IRule zoneAvoidanceRule() {
    
    
        return new ZoneAvoidanceRule();
    }

    private IRule randomRule() {
    
    
        return new RandomRule();
    }
复制代码

Instead of using RibbonClient.create() to create the default RibbonClient, get feign.ribbon.Builder through RibbonClient.builder(), and then set the implementation of LBClientFactory to customize LBClient. You can specify the load strategy in the process of creating LBClient Implementation.

share resources

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-tay3QQq8-1691467722037)(https://pic.imgdb.cn/item/64d0dc6a1ddac507cc857b30.png)]Get the
above For resources, please visit the open source project and click to jump

Guess you like

Origin blog.csdn.net/star20100906/article/details/132164163