上一章搭建完成了eureka服务中心与客户端 并且调用客户端成功
但当用户访问量过多的时候,服务压力会过大,会有出现服务宕机的情况。为保证服务的健壮性,服务大多以集群方式比较好。
这一章开始使用ribbon来实现服务调用的负载均衡
一、创建ribbon-client项目
二、修改配置文件
spring.application.name=ribbon-client
# 应用服务 WEB 访问端口
server.port=8700
#服务中心地址
eureka.client.serviceUrl.defaultZone=http:localhost:8761/eureka/
三、在启动类上添加注解 @EnableEurekaClient
package com.example.ribbonclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class RibbonClientApplication {
public static void main(String[] args) {
SpringApplication.run(RibbonClientApplication.class, args);
}
}
四、添加配置类
package com.example.ribbonclient.config;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
@SpringBootConfiguration
@Component
public class RibbonConfiguration {
@Bean
//开启客户端负载均衡
@LoadBalanced
RestTemplate restTemplate(){
return new RestTemplate();
}
}
五、添加调用方法
package com.example.ribbonclient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RibbonController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/index")
public String index(){
return restTemplate.getForObject("http://eureka-client/index",String.class);
}
}
六、为显示负载均衡测试效果,再启动一个eureka-client服务
6.1 修改eureka-client配置的端口号 改为
server.port=8763
6.2 修改serviceimpl代码
package com.example.eurekaclient.service.impl;
import com.example.eurekaclient.service.IndexService;
import org.springframework.stereotype.Service;
@Service
public class IndexServiceImpl implements IndexService {
@Override
public String getMesasge() {
return "hello springcloud 8763";
}
}
6.3 开启idea多服务启动
六、刷新eureka服务监控中心并测试
页面多次刷新 测试负载均衡效果