spring boot 2.0 ribbon 负载均衡配置
1.pom.xml
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> <version>2.0.2.RELEASE</version> </dependency>
2.入口文件:UserConsumerDemoApplication.java
package cn.itcast.user; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @EnableDiscoveryClient @SpringBootApplication public class UserConsumerDemoApplication { @Bean @LoadBalanced //负载均衡 public RestTemplate restTemplate() { // 这次我们使用了OkHttp客户端,只需要注入工厂即可 return new RestTemplate(new OkHttp3ClientHttpRequestFactory()); } public static void main(String[] args) { SpringApplication.run(UserConsumerDemoApplication.class, args); } }
3.UserRibbonController.java
package cn.itcast.user.controller; import cn.itcast.user.pojo.User; import com.netflix.ribbon.Ribbon; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.List; @RestController @RequestMapping("consumerRobbon") public class UserRobbonController { @Autowired private RestTemplate restTemplate; @GetMapping("{id}") public User queryUserById(@PathVariable("id") Long id){ String url = "http://user-service/user/" + id; User user = restTemplate.getForObject(url, User.class); return user; } }