上篇SpringCloud系列(四)——Ribbon负载均衡介绍了Ribbon负载均衡,都是理论性的东西,接下来用代码实现一下。
@RequestMapping(value = "/person", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public Person getPerson(HttpServletRequest request){
Person p = new Person();
p.setId(1);
p.setName("小米");
p.setMessage(request.getRequestURL().toString());
return p;
}
public static void main(String[] args) throws Exception {
ConfigurationManager.getConfigInstance().setProperty(
"my-client.ribbon.listOfServers", "localhost:8080,localhost:8081");
RestClient client = (RestClient) ClientFactory.getNamedClient("my-client");
HttpRequest request = HttpRequest.newBuilder().uri(("/person")).build();
for(int i = 0;i<10;i++){
HttpResponse response = client.executeWithLoadBalancer(request);
String json = response.getEntity(String.class);
System.out.println(json);
}
}
{"id":1,"name":"小米","message":"http://localhost:8081/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8081/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8081/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8081/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8081/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
public class MyRule implements IRule {
private ILoadBalancer lb;
public Server choose(Object key) {
Random r= new Random();
int num = r.nextInt(10);
List servers = lb.getAllServers();
if(num > 7){
return getServerByPost(servers,8081);
}else{
return getServerByPost(servers,8080);
}
}
private Server getServerByPost(List servers,int port){
for(Server s:servers){
if(s.getPort() == port){
return s;
}
}
return null;
}
public void setLoadBalancer(ILoadBalancer lb) {
this.lb=lb;
}
public ILoadBalancer getLoadBalancer() {
return this.lb;
}
}
ConfigurationManager.getConfigInstance().setProperty(
"my-client.ribbon.NFLoadBalancerRuleClassName", MyRule.class.getName());
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8081/person"}
{"id":1,"name":"小米","message":"http://localhost:8081/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8080/person"}
{"id":1,"name":"小米","message":"http://localhost:8081/person"}