spring cloud客户端启用负载均衡

provider  

spring-lb-provider
@RequestMapping(value = "/call/{id}", method = RequestMethod.GET, 
			produces = MediaType.APPLICATION_JSON_VALUE)
	public Police call(@PathVariable Integer id, HttpServletRequest request) {
		Police p = new Police();
		p.setId(id);
		p.setName("angus");
		p.setMessage(request.getRequestURL().toString());
		return p;
	}

  consumer

@RestController
@Configuration
public class TestController {
	
	@Bean
	@LoadBalanced
	public RestTemplate getRestTemplate() {
		return new RestTemplate();
	}

	@GetMapping("/router")
	@ResponseBody
	public String router() {
		RestTemplate tpl = getRestTemplate();
		String json = tpl.getForObject("http://spring-lb-provider/call/1", String.class);
		return json;
	}
	
	@Autowired
	private LoadBalancerClient client;

	@RequestMapping(value = "/lb", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ServiceInstance lb() {
		ServiceInstance si = client.choose("spring-lb-provider");
		return si;
	}
	
	@Autowired
	private SpringClientFactory factory;
	
	@RequestMapping(value = "/fa", method = RequestMethod.GET)
	public String factory() {
		ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer)factory.getLoadBalancer("default");
		System.out.println(lb.getRule().getClass().getName());
		
		ZoneAwareLoadBalancer lb2 = (ZoneAwareLoadBalancer)factory.getLoadBalancer("spring-lb-provider");
		System.out.println(lb2.getRule().getClass().getName());
		return "";
	}
}

  

posted @ 2018-03-10 15:00  zfzf1  阅读(329)  评论(0编辑  收藏  举报