首先创建一个注册中心和两个服务调用方:
创建注册中心地址:https://blog.csdn.net/quguoxun/article/details/111030810
创建服务调用方地址:https://blog.csdn.net/quguoxun/article/details/111034298
基于以上项目复制client-01创建client-02并修改application.properties中端口为9092并启动
spring.application.name不修改,仍为client-01:
由于服务之间是根据此名称进行相互调用,所以此时表
示
9091,9092对外提供一个服务,
服务名为client-01相当于一个小的集群
访问地址:
http://localhost:9090/ 会出现两个调用方
创建一个服务消费者service-ribbon,创建方法:
在启动类中添加一个注解,并开启负载均衡功能(@LoadBalanced):
package com.joyin.serviceribbon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean
@LoadBalanced //通过LoadBalanced注解表明这个restRemplate开启负载均衡的功能
RestTemplate restTemplate() {
return new RestTemplate();
}
}
配置相关配置文件application.properties
#Eureka服务注册中心的访问地址
eureka.client.serviceUrl.defaultZone=http://localhost:9090/eureka/
#client服务的端口
server.port=9093
#clinet服务的服务名称
spring.application.name=server-ribbon
创建一个Controller类(RibbonController)和Service类(RibbonService)进行测试:
package com.joyin.serviceribbon.Service;
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 RibbonTest(String message) {
//使用注册到Eureka服务中心的客户端,由客户端分配具体调用哪个服务
return restTemplate.getForObject("http://client-01/ClientTest?message="+message,String.class);
}
}
package com.joyin.serviceribbon.Controller;
import com.joyin.serviceribbon.Service.RibbonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RibbonController {
@Autowired
RibbonService RibbonService;
@RequestMapping(value = "/RibbonTest")
public String hi(@RequestParam String message){
return RibbonService.RibbonTest(message);
}
}
启动进行负载均衡的服务server-ribbon:
查看服务注册中心是否有新增的服务:http://localhost:9090/
上图红框中的服务为新增的调用方。
下一步测试负载均衡是否生效:
浏览器上多次刷新http://localhost:9093/RibbonTest?message=“负载均衡测试”,
浏览器交替显示:"负载均衡测试"端口号:9091,"负载均衡测试"端口号:9092;
这说明我们通过调用
restTemplate.getForObject("http://client-01/ClientTest?message="+message,String.class);
方法时,已经做了负载均衡,访问了不同端口的服务实例。
到此,负载均衡案例测试完毕,需要的小伙伴动动你们的小手操作一下吧,实践才能出真知!!