SpringCloud系列课程第十七课-Ribbon负载均衡

. 在之前使用了一个"@LoadBalanced"注解,该注解描述的是一个负载均衡,但是对于负载均衡也是可以由用户修改负载均衡策略的。那么如果说现在要想去修改这样的策略也是可以的,可以使用自定义的LoadBalance配置类。

【microcloud-consumer-80】追加一个LoadBalance的配置类,这个类应该放在SpringCloud启动后找不到的位置上,所有应该做一个新的包:commons

3. 2

【microcloud-consumer-80】新建自定义负载均衡类:

public class MyLoadBalance {

@Bean

public IRule ribbonRule() {//其中IRule是所有规则的标准

return new RandomRule();

}

}

4. 3

【microcloud-consumer-80】修改程序主类,追加Ribbon的配置操作:

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

@EnableEurekaClient

@RibbonClient(name="ribbonClient",configuration = MyLoadBalance.class)

public class Consumer_80_StartSpringCloudApplication {

public static void main(String[] args) {

SpringApplication.run(Consumer_80_StartSpringCloudApplication.class,args);

}

}

5. 4

输入地址:http://client.com/consumer/dept/list

查看客户端端的访问策略是不是随机的。

6. 5

【microcloud-consumer-80】修改控制器程序类,在这个程序类之中可以通过负载均衡的客户端获取服务器的相关信息。

import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;

import java.util.List;

@RestController

public class ConsumerDeptController {

public static final String DEPT_GET_URL = "http://MICROCLOUD-PROVIDER-DEPT/dept/get/";

public static final String DEPT_LIST_URL = "http://MICROCLOUD-PROVIDER-DEPT/dept/list/";

public static final String DEPT_ADD_URL = "http://MICROCLOUD-PROVIDER-DEPT/dept/add";

@Resource

private RestTemplate restTemplate;

@Resource

private HttpHeaders httpHeaders;

@Resource

private LoadBalancerClient loadBalancerClient;

@RequestMapping(value = "/consumer/dept/get",method = RequestMethod.GET)

public Object getDept(long id) {

ServiceInstance serviceInstance = this.loadBalancerClient.choose("MICROCLOUD-PROVIDER-DEPT");

serviceInstance.getPort() + ",serviceId" + serviceInstance.getServiceId());

//Dept dept = this.restTemplate.getForObject(DEPT_GET_URL + id,Dept.class);

Dept dept = this.restTemplate.exchange(DEPT_GET_URL + id, HttpMethod.GET,

new HttpEntity(this.httpHeaders),Dept.class).getBody();

return dept;

}

@RequestMapping(value = "/consumer/dept/list")

public Object listDept() {

//List allDepts = this.restTemplate.getForObject(DEPT_LIST_URL,List.class);

List allDepts = this.restTemplate.exchange(DEPT_LIST_URL,HttpMethod.GET,

new HttpEntity(this.httpHeaders),List.class).getBody();

return allDepts;

}

@RequestMapping(value = "/consumer/dept/add")

public Object addDept(Dept dept) {

return this.restTemplate.exchange(DEPT_ADD_URL,HttpMethod.POST,

new HttpEntity(dept,this.httpHeaders),Boolean.class).getBody();

}

}

7. 6

输入地址:http://client.com/consumer/dept/get?id=1

查看控制台输出结果。

  • 发表于:
  • 原文链接:http://kuaibao.qq.com/s/20180119A02YJR00?refer=cp_1026

扫码关注云+社区