ribbon客户端负载均衡

411 阅读1分钟
  1. ribbon默认的负载均衡策略是循环请求应用,修改策略是在调用方的application.yml配置中设置。
  2. ribbon会存储注册中心应用,然后定时去更新,而不是每次都要先访问注册中心,再访问应用

  1. 依赖
                <dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
		</dependency>
  1. 配置RestTemplate

	/**
	 * @Bean是一个方法级别上的注解,
	 * 主要用在@Configuration注解的类里,
	 * 也可以用在@Component注解的类里。
	 * 添加的bean的id为方法名
	 */
	
	@Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		return new RestTemplate();
	}
  1. 在service中注入RestTemplate, 注意:url参数中,只需要应用名,不需要端口

	        @Resource
	        private RestTemplate restTemplate;
	

		//注意:只需要应用名称(不区分大小写),不需要端口
		String url=String.format("http://%s/api/v1/product/queryProductByIds?ids=%d", APP_NAME_PRODUCT, Integer.parseInt(map.get("productId").toString()));
		
		List list=restTemplate.getForObject(url, List.class);
		logger.info("ribbon 查询返回结果:{}", JSON.toJSONString(list));
		if(list!=null && list.size()>0) {
			orderMapper.saveOrder(map);
		}