Skip to content

启用 RestTemplate 支持负载均衡器

配置 RestTemplate 负载均衡器

java
package cloud.xuxiaowei.loadbalancer.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * 启用 {@link RestTemplate} 注入支持负载均衡器
 *
 * @author xuxiaowei
 * @since 0.0.1
 */
@Configuration
public class RestTemplateLoadBalancedConfig {

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}

使用 RestTemplate 负载均衡器

java
package cloud.xuxiaowei.passport.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@RestController
public class IndexRestController {

    private RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping
    public Map<String, Object> index() {
        // 调用 user 服务的 /info 接口
        return restTemplate.getForObject("http://user/info", Map.class);
    }

}