您好,登录后才能下订单哦!
这篇文章给大家分享的是有关SpringCloud中怎么使用Ribbon和RestTemplate实现服务调用和负载平衡的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
SpringCloud 是目前微服务架构领域的翘楚,备受开发者和企业的青睐。
文件目录结构很重要,特别注意的是rule文件要放在主启动类上一级位置,才能够扫描。
<dependencies>
<!--springboot 2.2.2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Spring cloud Hoxton.SR1-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--Spring cloud alibaba 2.1.0.RELEASE-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--Eureka-Client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
因为eureka的依赖已经整合了ribbon的依赖,所以不用额外引入新的东西。
server: port: 80 spring: application: name: cloud-book-consumer eureka: client: register-with-eureka: false fetch-registry: true service-url: defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "CLOUD-BOOK-SERVICE", configuration = LoadBalanceRule.class) //更换轮询算法
public class RestTemplateMain80 {
public static void main(String[] args) {
SpringApplication.run(RestTemplateMain80.class,args);
}
}
在图示文件目录下新建LoadBalanceRule.class,用于更换负载均衡算法。
@Configuration
public class LoadBalanceRule {
@Bean
public IRule iRule() {
// 定义为随机
return new RandomRule();
}
}
开启restTemplate负载均衡
在config文件夹下创建LoadBalanceConfig.class
@Configuration
public class LoadBalanceConfig {
@Bean
@LoadBalanced //开启负载均衡
public RestTemplate getReatTemplate(){
return new RestTemplate();
}
}
新建BookController.class
写业务代码
@RestController
@Slf4j
public class BookController {
@Resource
private RestTemplate restTemplate;
public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";
@GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
public CommonResult getAllBooks(){
return restTemplate.getForObject(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
}
@GetMapping("restTemplate/book/getAllBooks2") //需要知道更多数据时,使用getForEntity方法
public CommonResult getAllBooks2(){
ResponseEntity<CommonResult> resultResponseEntit = restTemplate.getForEntity(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
if (resultResponseEntit.getStatusCode().is2xxSuccessful()){
log.info(resultResponseEntit.getStatusCode()+" "+resultResponseEntit.getHeaders());
return resultResponseEntit.getBody();
}else {
return new CommonResult<>(444,"操作失败");
}
}
@GetMapping(value = "restTemplate/book/index")
public String index() {
return restTemplate.getForObject(PAYMENT_URL+"/book/index",String.class);
}
}
使用restTemplate+Ribboin实现服务调用和负载均衡完成。
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
@Component
public class MyLB implements LoadBalancer {
private AtomicInteger atomicInteger = new AtomicInteger(0);
//求第几次访问 自旋锁思想
public final int getAndIncrement(){
int current;
int next;
do {
current = this.atomicInteger.get();
next = current >=2147483647 ? 0 : current+1;
}while(!this.atomicInteger.compareAndSet(current,next));
System.out.println("***第几次访问next->"+next);
return next;
}
//负载均衡算法,实现roundRobin算法
@Override
public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
int index = getAndIncrement() % serviceInstances.size();
return serviceInstances.get(index);
}
}
@RestController
@Slf4j
public class BookController {
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";
@GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
public CommonResult getAllBooks(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE");
if (instances == null || instances.size() <= 0){
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/book/getAllBooks",CommonResult.class);
}
@GetMapping(value = "restTemplate/book/index")
public String index() {
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE");
if (instances == null || instances.size() <= 0){
return null;
}
ServiceInstance serviceInstance = loadBalancer.instances(instances);
URI uri = serviceInstance.getUri();
return restTemplate.getForObject(uri+"/book/index",String.class);
}
}
删去主启动类的更换负载均衡算法注解
@RibbonClient(name = “CLOUD-BOOK-SERVICE”, configuration = LoadBalanceRule.class)
删去LoadBalanceConfig中开启负载均衡算法注解
@LoadBalanced
手写Ribbon算法并使用完成
感谢各位的阅读!关于“SpringCloud中怎么使用Ribbon和RestTemplate实现服务调用和负载平衡”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。