1. Concept: Ribbon load Balancing
2. Specific content
Now that all the services have been registered through Eureka, then the purpose of using Eureka registration is to want all the services to be unified into the Eureka processing, but now the problem, all the microservices into the Eureka, and the client's call should also pass Eureka completed. This invocation can be implemented using the Ribbon technology.
The Ribbon is a component of a service invocation and is a component of a client that implements load balancing processing . Server-side implementation of load balancing can use Nginx, HAProxy, LVS and so on.
2.1, the basic use of the Ribbon
1, "microcloud-consumer-80" Modify the Pom.xml configuration file, append Ribbon dependent support package:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId> spring-cloud-starter-eureka</artifactid> </dependency> <dependency> <groupid >org.springframework.cloud</groupId> <artifactid>spring-cloud-starter-config</artifactid > </dependency> <dependency> <groupid>org.springframework.cloud</groupid > <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency>
2. "Microcloud-consumer-80" modifies the Restconfig configuration class and joins the Ribbon's configuration annotations @loadbalanced when acquiring Resttemplate objects.
Package Cn.study.microcloud.config;import Java.nio.charset.charset;import Java.util.base64;import Org.springframework.cloud.client.loadbalancer.loadbalanced;import Org.springframework.context.annotation.Bean; Import Org.springframework.context.annotation.configuration;import Org.springframework.http.httpheaders;import org.springframework.web.client.RestTemplate; @Configurationpublic class Restconfig {@Bean public httpheaders GetHead ERs () {///To make an HTTP header message configuration httpheaders headers = new Httpheaders ();//define an HTTP header message String auth = "Studyjava: Hello "; The original information of the authentication byte[] Encodedauth = Base64.getencoder (). Encode (Auth.getbytes (Charset.forname ("Us-ascii" ))); Perform an encrypted processing//When authorizing the configuration of the header information content the encrypted information must have a space between the "basic" string authheader = "Basic" + new string (Encodedaut h); Headers.set ("Authorization", Authheader); return headers; } @Bean @LoadBalanced public resttemplate getresttemplate () {return new resttemplate(); }}
3, "microcloud-consumer-80" Modify the aplication.yml configuration file, append the Eureka service registration address configuration.
Server: Port:80eureka: client: register-with-eureka:false #客户端不注册到eureka, just a call to the service Service-url: Defaultzone:http://edmin:[email Protected]:7001/eureka,http://edmin:[email protected]:7002/eureka,http:// Edmin:[email Protected]:7003/eureka
4, "microcloud-consumer-80" Modify the startup class of the project, append the configuration annotations of the Eureka client:
Package Cn.study.microcloud;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.cloud.client.discovery.enablediscoveryclient;import Org.springframework.cloud.netflix.eureka.EnableEurekaClient, @SpringBootApplication @enableeurekaclientpublic Class Consumer_80_startspringcloudapplication {public static void Main (string[] args) { Springapplication.run (Consumer_80_startspringcloudapplication.class, args);} }
5, "microcloud-consumer-80" Modify the controller call class;
· The names of all services registered in Eureka are now uppercase letters: microcloud-provider-dept;
Package Cn.study.microcloud.controller;import Java.util.list;import Javax.annotation.resource;import Org.springframework.cloud.netflix.ribbon.ribbonclient;import Org.springframework.http.httpentity;import Org.springframework.http.httpheaders;import Org.springframework.http.httpmethod;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import org.springframework.web.client.RestTemplate; Import cn.study.vo.Dept; @RestControllerpublic class Consumerdeptcontroller {public static final String Dept_get_url = "http://MICROCLOUD-PROVIDER-DEPT/dept/get/"; public static final String Dept_list_url = "http://MICROCLOUD-PROVIDER-DEPT/dept/list/"; public static final String Dept_add_url = "Http://MICROCLOUD-PROVIDER-DEPT/dept/add?dname="; @Resource private Resttemplate resttemplate; @Resource private httpheaders headers; @RequestMapping (value = "/consumer/dept/get") public Object getdept (long id) { Dept Dept = this.resttemplate. Exchange (Dept_get_url + ID, httpmethod.get, new Ht Tpentity<object> (this.headers), Dept.class). GetBody (); return dept; } @SuppressWarnings ("Unchecked") @RequestMapping (value = "/consumer/dept/list") public Object listdept () { List<dept> alldepts = this.resttemplate. Exchange (Dept_list_url, Httpmethod.get, New Httpentity<object> (this.headers), List.class). GetBody (); return alldepts; } @RequestMapping (value = "/consumer/dept/add") Public Object adddept (Dept Dept) throws Exception {Boolean F lag = This.restTemplate.exchange (Dept_add_url, Httpmethod.post, New httpentity<object> (DEPT, This.hea ders), Boolean.class). GetBody (); return flag; }}
Access address: Http://client.com/consumer/dept/list. This time with the Ribbon and Eureka after the integration of the user no longer pay attention to the specific Rest service address and port number, all the information is obtained through Eureka complete.
2.2. Ribbon Load Balancing
The above code shows that there is a load-balanced annotation in the Ribbon: @LoadBalanced, it means that load balancing can now be done. The schematic diagram of the ribbon load balancer is as follows
All services are registered to the Eureka Center, and all are the same name microcloud-provider-dept, the user finds the service microcloud-provider-dept through Eureka, and then calls through the ribbon load Balancer
1, "microcloud-provider-dept-8001" to copy this project as two copies of "microcloud-provider-dept-8002", "microcloud-provider-dept-8003";
2, "microcloud-provider-dept-*" to execute their own database scripts, and then modify their respective database connection configuration;
3, "microcloud-provider-dept-*" to modify the respective service application.yml configuration file;
Server:port:8001eureka:client: # client Eureka registered configuration Service-url:defaultzone:http://edmin:[email protecte D]:7001/eureka,http://edmin:[email protected]:7002/eureka,http://edmin:[email protected]:7003/eureka Instance:lease-renewal-interval-in-seconds:2 # Set the heartbeat time interval (default is 30 seconds) Lease-expiration-duration-in-seconds:5 # If it's over now 5-second interval (default is 90 seconds) instance-id:dept-8001.com # Displays the host name in the information list Prefer-ip-address:true # The path of the access becomes the IP address info:app.name:s Tudy-microcloud company.name:www.study.cn Build.artifactid: $project. artifactid$ build.version: $project. verson$ Mybatis:config-location:classpath:mybatis/mybatis.cfg.xml # MyBatis configuration file is located on the path Type-aliases-package:cn.study.vo # define the alias of all operation Classes package mapper-locations: # All Mapper mapping files-classpath:mybatis/mapper/* */*.xmlspring:datasource:type:com.alibaba.druid.pool.druiddatasource # Configure the type of operation for the data source you are currently using Driver-class-name:or G.gjt.mm.mysql.driver # Configuring the MySQL DriverOrder Class URL:JDBC:MYSQL://LOCALHOST:3306/STUDY8001 # Database connection Address Username:root # Database user name Password:mysqladmin # database connection password DBCP2: # Enter Configuration of the row database connection pool Min-idle:5 # Minimum number of maintenance connections for the database connection pool Initial-size:5 # Initialize the number of connections provided Max-total:5 # Maximum number of connections max-wait-millis:200 # Wait for connection to get the maximum timeout time application:name:microcloud-provider-dept
Remember, now all service names must be consistent, and if not inconsistent, will be considered two services and cannot be load balanced.
4. Modify the hosts configuration file in the project and append the new domain name to the configuration file:
127.0.0.1 dept-8001.com127.0.0.1 dept-8002.com127.0.0.1 dept-8003.com
5, "microcloud-provider-dept-*" to ensure that the Eureka has been properly activated after the start of all the department micro-Service information;
6, "Microcloud-consumer" Start the consumer end, the consumer in the Resttemplate configuration when the use of load-balanced annotations.
· Access address: http://client.com/consumer/dept/list;
Now that each acquisition is achieved through a different microservices, the same consumer can now load-balance configuration processing through the Ribbon.
2.3. Custom Ribbon Configuration
A "@LoadBalanced" annotation was previously used, which describes a load balancer, but the load balancing policy can also be modified by the user for load balancing. Then if you want to modify such a policy now, it is also possible to use the custom Loadbalacne configuration class.
1, "microcloud-consumer-80" Append a LoadBalance configuration class, this class should be placed in the Springcloud can not find the location, so should make a new package;
Package Cn.study.commons.config;import Org.springframework.context.annotation.bean;import Com.netflix.loadbalancer.irule;public class Myloadbalanceconfig { @Bean public IRule Ribbonrule () {// Where Irule is the standard of all rules return new Com.netflix.loadbalancer.RandomRule ();} }
2, "microcloud-consumer-80" Modify the program main class, append the Ribbon configuration operation:
Package Cn.study.microcloud;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.cloud.client.discovery.enablediscoveryclient;import Org.springframework.cloud.netflix.eureka.enableeurekaclient;import Org.springframework.cloud.netflix.ribbon.ribbonclient;import cn.study.commons.config.myloadbalanceconfig;@ Springbootapplication@enableeurekaclient@ribbonclient (name= "Ribbonclient", configuration= Myloadbalanceconfig.class) public class Consumer_80_startspringcloudapplication {public static void main (string[ ] args) { springapplication.run (Consumer_80_startspringcloudapplication.class, args);} }
At this point, the load balancing configuration processing operation is implemented.
3, "microcloud-consumer-80" Modify the Controller program class, in this program class can be load-balanced client to obtain information about the server.
Package Cn.study.microcloud.controller;import Java.util.list;import Javax.annotation.resource;import Org.springframework.cloud.client.serviceinstance;import Org.springframework.cloud.client.loadbalancer.loadbalancerclient;import org.springframework.http.HttpEntity; Import Org.springframework.http.httpheaders;import Org.springframework.http.httpmethod;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import org.springframework.web.client.RestTemplate; Import cn.study.vo.Dept; @RestControllerpublic class Consumerdeptcontroller {public static final String Dept_get_url = "http://MICROCLOUD-PROVIDER-DEPT/dept/get/"; public static final String Dept_list_url = "http://MICROCLOUD-PROVIDER-DEPT/dept/list/"; public static final String Dept_add_url = "Http://MICROCLOUD-PROVIDER-DEPT/dept/add?dname="; @Resource private Resttemplate resttemplate; @Resource private httpheaders headers; @Resource Private loadbalancerclient loadbalancerclient; @RequestMapping (value = "/consumer/dept/get") public Object getdept (long id) {Serviceinstance serviceinstance = This.loadBalancerClient.choose ("microcloud-provider-dept"); SYSTEM.OUT.PRINTLN ("* * * * * * serviceinstance" host = "+ serviceinstance.gethost () + ", port =" + serviceinstance.getport () + ", ServiceId =" + Serviceinstance.getserviceid ()); Dept Dept = this.resttemplate. Exchange (Dept_get_url + ID, httpmethod.get, new Htt Pentity<object> (this.headers), Dept.class). GetBody (); return dept; } }
At this point in the background through the specified load-balanced configuration program, you can get the information of the host that will be operational.
2.4. Disable Eureka Implementation Ribbon call
The previously used technique was to obtain the required data by Eureka accessing the service of the specified name in Eureka, but the Ribbon was designed with an environment that was out of Eureka use. If the Eureka is to be truly detached, the code will become the following form.
1, "Microcloud-consumer-ribbon" Modify the application.yml configuration file:
Server: Port:80ribbon: Eureka: enabled:falsemicrocloud-provider-dept: Ribbon: listofservers:http://dept-8001.com:8001,http://dept-8002.com:8002,http://dept-8003.com:8003
2, "Microcloud-consumer-ribbon" Modify the Restconfig Configuration Program class, no longer need to use "@LoadBalanced" annotations:
Package Cn.study.microcloud.config;import Java.nio.charset.charset;import Java.util.base64;import Org.springframework.cloud.client.loadbalancer.loadbalanced;import Org.springframework.context.annotation.Bean; Import Org.springframework.context.annotation.configuration;import Org.springframework.http.httpheaders;import org.springframework.web.client.RestTemplate; @Configurationpublic class Restconfig {@Bean public httpheaders GetHead ERs () {///To make an HTTP header message configuration httpheaders headers = new Httpheaders ();//define an HTTP header message String auth = "Studyjava: Hello "; The original information of the authentication byte[] Encodedauth = Base64.getencoder (). Encode (Auth.getbytes (Charset.forname ("Us-ascii" ))); Perform an encrypted processing//When authorizing the configuration of the header information content the encrypted information must have a space between the "basic" string authheader = "Basic" + new string (Encodedaut h); Headers.set ("Authorization", Authheader); return headers; } @Bean//@LoadBalanced public resttemplate getresttemplate () {return new ResttemplAte (); }}
3, "Microcloud-consumer-ribbon" Modify the Consumerdeptcontroller controller, directly through the acquisition of host and Port to invoke the background micro-service:
Package Cn.study.microcloud.controller;import Java.net.uri;import Javax.annotation.resource;import Org.springframework.cloud.client.serviceinstance;import Org.springframework.cloud.client.loadbalancer.loadbalancerclient;import Org.springframework.cloud.netflix.ribbon.ribbonclient;import Org.springframework.http.httpentity;import Org.springframework.http.httpheaders;import Org.springframework.http.httpmethod;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import org.springframework.web.client.RestTemplate; Import Cn.study.commons.config.myloadbalanceconfig;import cn.study.vo.Dept; @RestController @ribbonclient (name = " Microcloud-provider-dept ", configuration = myloadbalanceconfig.class) public class Consumerdeptcontroller {public stat IC final String dept_rest_topic = "Microcloud-provider-dept"; @Resource private Resttemplate resttemplate; @Resource private httpheaders headers; @Resource Private Loadbalancerclient loadbalancerclient; @RequestMapping (value = "/consumer/dept/get") public Object getdept (long id) {Serviceinstance serviceinstance = This.loadbalancerclient. Choose (dept_rest_topic); SYSTEM.OUT.PRINTLN ("* * * * * * serviceinstance" host = "+ serviceinstance.gethost () + ", port =" + serviceinstance.getport () + ", ServiceId =" + Serviceinstance.getserviceid () + ", Uri =" + Serviceinstance.geturi ()); URI Depturi = uri.create (String.Format ("http://%s:%s/dept/get/" + ID, serviceinstance.gethost (), Serviceins Tance.getport ())); Dept Dept = this.resttemplate. Exchange (Depturi, Httpmethod.get, new Httpentity<o Bject> (this.headers), Dept.class). GetBody (); return dept; }}
This model is not standard, can only be said to be the ribbon itself has a function, in fact, if not very necessary, is not recommended to use.
Score of
Springcloud series five: Ribbon load balancing (ribbon basic use, ribbon load balancer, custom Ribbon configuration, disable Eureka implementation ribbon call)