Brief introduction
rest Template
Spring core classes for synchronization client end, simplifies communication and http service and to meet RESTful principles, program code may provide a URL to it, and the extraction result. By default, RestTemplate jdk dependent default HTTP connection tool.
Ribbon
Spring Cloud Ribbon is based on HTTP and TCP client load balancing tool, which implements based Netflix Ribbon. By Spring Cloud package, it allows us to easily service-oriented REST template automatically converted to service calls requesting client load balancing. Spring Cloud Ribbon exists in almost every Spring Cloud Service and build micro-infrastructure. Because the calls between micro-services, API gateway forwards the request to other content, are actually implemented by the Ribbon, including Feign, it is also based tool Ribbon implemented.
In Spring Cloud, the Ribbon when used in conjunction with Eureka, Ribbon can be acquired from Eureka Server service provider address list and load balancing algorithm, select a service provider instance.
Start registration centers and service providers
https://blog.csdn.net/miaodichiyou/article/details/104160284
1, start the registration center SpringCloud high availability service registry (Eureka) built
2, add a controller in springcloud-eureka-provider Hi_provider.java project file, external services "/ hi"
package org.springcloud.eureka.provider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableEurekaClient
public class Hi_provider
{
public static void main( String[] args )
{
SpringApplication.run(Hi_provider.class, args);
}
@RestController
public class HiController {
@Value("${server.port}")
String port;
@GetMapping("/hi")
public String Home(@RequestParam String name){
return "hi "+name+",This is from serverport:"+port;
}
}
}
Start three springcloud-eureka-provider instance, ports 8001,8002 and 8003, respectively
Create a service consumer
Add file dependencies POM.xml
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.springcloud</groupId>
<artifactId>springcloud-root</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>springcloud-ribbon</artifactId>
<name>springcloud-ribbon</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application.yml configuration file
spring:
application:
name: springcloud-ribbon
freemarker:
prefer-file-system-access: false
security:
user:
name: admin
password: 123456
server:
port: 8100
eureka:
instance:
hostname: eureka-ribbon.com
instance-id: eureka-ribbon
client:
service-url:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@eureka-peer1.com:8897/eureka/,http://${spring.security.user.name}:${spring.security.user.password}@eureka-peer2.com:8898/eureka/,http://${spring.security.user.name}:${spring.security.user.password}@eureka-peer3.com:8899/eureka/
Modify C: \ Windows \ System32 \ drivers \ etc \ hosts
127.0.0.1 eureka-ribbon.com
Add a service consumer class start
- RibbonApplication.java
package org.springcloud.ribbon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RibbonApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}
Adding RESTful API Interface
Call springcloud-eureka-provider instance API interface "/ hi", namely consumer services. Since springcloud-eureka-provider three instances (port 8001,8002,8003), hope to do take turns to access the three instances when you call, then we need to RestTemplate and Ribbon combined with load balancing. Only need to be injected in the IOC container program a restTemplate of Bean, plus @LoadBalanced comment at this time RestTemplate it combines the Ribbon open load balancing.
- RestTemplateConfig.java
package org.springcloud.ribbon;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(30000);
httpRequestFactory.setConnectTimeout(30000);
httpRequestFactory.setReadTimeout(30000);
return new RestTemplate(httpRequestFactory);
}
}
Add the service consumer service provided by the service provider instance
Write a RibbonService class in hi class () method call with restTemplate springcloud-eureka-provider API interface, without the use of hard-coded (such as IP address) on uri, simply write the service name springcloud-eureka-provider to .
- RibbonService.java
package org.springcloud.ribbon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RibbonService {
@Autowired
RestTemplate restTemplate;
public String hi(String name){
return restTemplate.getForObject("http://springcloud-eureka-provider/hi?name="+name,String.class);
}
}
Note: url springcloud-eureka-provider getForObject in for springcloud-eureka-provider program (service provider) application name, which is spring.application.name configured in the configuration file when creating springcloud-eureka-provider item = springcloud-eureka-provider. hi address (controller) springcloud-eureka-provider interface item, name is requested parameter.
Create a controller, the method call service
Write a RibbonController class
package org.springcloud.ribbon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RibbonController {
@Autowired
private RibbonService ribbonService;
@GetMapping("/hi")
public String hi(@RequestParam(required = false,defaultValue = "zhaojq") String name){
return ribbonService.hi(name);
}
}
Start springcloud-ribbon project
View Eureka registry
Run startup class, visit http://eureka-peer1.com:8897/
http://eureka-peer2.com:8898/,http://eureka-peer3.com:8899/ results above.
Examples of consumer service has been successfully registered.
controller in the browser address bar to access ribbon project
In the browser several times to access http: // localhost: 8100 / hi name = zhaojq, the browser will display the following turn?
When has been refreshed http: // localhost: 8100 / hi browser alternates can be found when the port name = zhaojq? 8001,8002 and 8003, indicating that the client has load balancing, and Ribbon default load balancing algorithm polling .
Ribbon load balancing strategy
Custom load balancing strategy (random policy)
Application.yml modify configuration files springcloud-ribbon project to add the following configuration:
# 自定义配置负载均衡策略
Load_Balance:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
Load_Balance address the need for the service load, com.netflix.loadbalancer.RandomRule service strategy. Here we configure random tactics
Modify RestTemplateConfig configuration class:
@Bean
public IRule ribbonRule() {
return new RandomRule();//实例化与配置文件对应的策略类
}
Modify RibbonController
package org.springcloud.ribbon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RibbonController {
@Autowired
private RibbonService ribbonService;
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/hi")
public String hi(@RequestParam(required = false,defaultValue = "zhaojq")String name){
this.loadBalancerClient.choose("Load_Balance");
return ribbonService.hi(name);
}
}
LoadBalancerClient (RibbonLoadBalancerClient is the implementation class) during initialization (execute methods), will pass ILoadBalance (BaseLoadBalancer is the implementation class) to obtain the service registration list to the Eureka registration center, and a send "ping", to determine the availability of services to EurekaClient every 10s If you change or service and the number of prior inconsistent availability of the service took place, from the registry update or re-pull. LoadBalancerClient With these service registration list, you can load balance based on specific IRule.
Restart springcloud-ribbon project, visit http://eureka-ribbon.com:8100/hi?name=zhaojq
In the command window curl http://eureka-ribbon.com:8100/hi, Ribbon has been found to achieve random load balancing strategy