ribbon简介
Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies. —–摘自官网
ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。
新建Ribbon工程
引入相关依赖
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> </dependencies>
application.yml
1 2 3 4 5 6 7 8 9 10 11 12 server: port: 8788 spring: application: name: ribbon-service eureka: client: service-url: defaultZone: http: instance: instance-id: ribbon-service:${server.port} prefer-ip-address: true
启动类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.client.loadbalancer.LoadBalanced;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;import org.springframework.context.annotation.Bean;import org.springframework.web.client.RestTemplate;@SpringBootApplication @EnableEurekaClient public class RibbonServerApplication { public static void main (String[] args) { SpringApplication.run(RibbonServerApplication.class,args); } @Bean @LoadBalanced RestTemplate restTemplate () { return new RestTemplate(); } }
service 层
1 2 3 4 5 6 7 8 9 10 11 12 13 import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;@Service public class UserService { @Autowired private RestTemplate restTemplate; public Object getList () { return restTemplate.getForObject("http://USER-SERVICE/user/list" ,Object.class); } }
controller层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 import com.felix.project.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController @RequestMapping (value = "/user" )public class UserController { @Autowired private UserService userService; @GetMapping (value = "/list" ) public Object getList () { return userService.getList(); } }
启动查看
1 http://localhost:8788/user/list
多次请求 http://localhost:8788/user/list 发现端口号相互交换,达到了负载均衡的作用。