provider cluster and load balancing ribbon
Previous: Feign's log
Next: Use zuul to build a microservice gateway
provider cluster.
I use the second startup method. Modify the application.yml configuration file, or use-to separate the different files in the file as follows:
#当前项目启动端口
#server:
# port: 8000
#连接数据库的信息
# generate-ddl: false 取消让它自动见数据库
# show-sql: true展示sql
spring:
jpa:
generate-ddl: false
show-sql: true
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/cloud?useUnicode=true&characterEncoding=UTF-8&useSSL=true
driver-class-name: com.mysql.jdbc.Driver
#当前启动的名字
profiles:
active: provider2
# application:
# name: springcloud-provider
info:
head: head
body: body
app:
name: @project.artifactId@
encoding: @project.build.sourceEncoding@
java:
source: @java.version@
target: @java.version@
management:
endpoints:
web:
exposure:
#加载所有的端点,默认只加载了info、health
include: '*'
endpoint:
health:
show-details: always
#可以关闭指定的端点
shutdown:
enabled: false
eureka:
client:
service-url:
defaultZone: http://root:root@peer1:8761/eureka/,http://root:root@peer2:8762/eureka/
instance:
prefer-ip-address: true
# virtual-host-name: provider
---
spring:
profiles: provider1
application:
name: provider
server:
port: 8000
---
spring:
profiles: provider2
application:
name: provider
server:
port: 8001
After startup,
test whether the provider provides services normally
http://localhost:8000/user/2
http://localhost:8001/user/2
is it registered to the service discovery component, as shown in the figure
Load balancing ribbon
Come a request, assign the request to the corresponding service consumer to make a request, judge which provider to get the data and return the data?
1 jar package, which has been introduced in eureka-client.
2 Add @LoadBalanced annotation to restTemplate on startup main class
@SpringBootApplication
@EnableEurekaClient
public class SpringcloudConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(SpringcloudConsumerApplication.class, args);
}
}
Modify the consumer's access path. After the provider has completed the cluster, the configuration file has changed. It can only be accessed through the provider's application name (also called serviceId), which is the provider's as shown in the figure:
Modify the consumer's UserController The path is as follows:
@RequestMapping("/user/{id}")
public User findUserById(@PathVariable("id") Integer id){
//消费者,调用生产者
// User user = restTemplate.getForObject(userServiceUrl+id,User.class);
User user = restTemplate.getForObject("http://provider/"+id,User.class);
return user;
}
The test consumer visits the provider
Four times as follows: the two providers each call twice. The
default load balancing is polling (I emptied the console for more intuitiveness). It is not the same as Dubbo's default random.
Types of load balancing algorithms
The core component of Ribbon is IRule, which is the parent interface of all load balancing algorithms. Its subclasses are:
RoundRobinRule Polling
RandomRule Random
AvailabilityFilteringRule will first filter out services that are in the circuit breaker trip state due to multiple access failures, as well as services whose number of concurrent connections exceeds the threshold, and then poll the remaining service list.
WeightedResponseTimeRule weights are based on the average response time Calculate the weights of all services, the faster the response time, the higher the service weight, the higher the probability of being selected. At the
beginning , if the statistical information is insufficient, the polling strategy is used, and when the information is sufficient, switch to WeightedResponseTimeRule RetryRule Retry to obtain the service according to the polling strategy first, if the acquisition fails, retry within the specified time to obtain the available service
BestAvailableRule Select filter
Remove the service that is in the circuit breaker trip state due to multiple access failures, and then select a service with the least concurrency, ZoneAvoidanceRule, which meets the performance of the area where the server is located and the availability of the server.
Custom configuration load balancing algorithm
There are two ways
One, JAVA configuration
The configuration is simple
public class SpringcloudConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
/**自定义配置ribbon负载均衡算法
* @return
*/
@Bean
public IRule myRule(){
// return new RoundRobinRule();//轮询
return new RandomRule();
// return new RetryRule();//重试
// return new BestAvailableRule();
}
public static void main(String[] args) {
SpringApplication.run(SpringcloudConsumerApplication.class, args);
}
}
The results of the (random) provider’s console input are as follows: I have
visited eight times and the
others are listed one by one.
You can select the appropriate algorithm for specific business requirements, and of course you can write an algorithm class based on specific business requirements.
Use configuration files to implement load balancing strategies
Two, attribute configuration
Add in the configuration file in the consumer project
#指定负载均衡策略
springcloud-consumer:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule
ribbon configuration priority: Ribbon configuration priority: attribute configuration> JAVA configuration
java configuration
attribute configuration
Follow polling as follows:
Ribbon configuration is roughly complete.
Log output
Use logs in the controller layer of the consumer project.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestController
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(User.class);
@Autowired
private LoadBalancerClient loadBalancerClient;
@Autowired
private UserFeignClient userFeignClient;
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServiceUrl}")
private String userServiceUrl;
@RequestMapping("user/{id}")
public User findById(@PathVariable("id") Integer id){
return restTemplate.getForObject("http://provider/user/"+id, User.class);
// return restTemplate.getForObject(userServiceUrl+id,User.class);
}
@GetMapping("/log")
public void logUserInstance(){
//虚拟主机名
ServiceInstance serviceInstance = this.loadBalancerClient.choose("provider");
this.logger.info("{}:{}:{}", serviceInstance.getInstanceId(),serviceInstance.getHost(),serviceInstance.getPort(),serviceInstance.getInstanceId());
}
}
Test:
When you visit the provider, the provider will print the host address of the port and so on.