本文共 3512 字,大约阅读时间需要 11 分钟。
本文搭建一个Ribbon实现负载均衡的效果
pom文件:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.1.1.RELEASE com.zsy.cloud cloud-ribbon 0.0.1-SNAPSHOT jar cloud-ribbon http://maven.apache.org 1.8 Greenwich.M3 org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-ribbon org.springframework.cloud spring-cloud-starter-netflix-eureka-client junit junit 3.8.1 test org.springframework.cloud spring-cloud-dependencies ${spring-cloud.version} pom import org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone false
properties文件:
server.port=2222spring.application.name=ribboneureka.client.service-url.defaultZone=http://register1:8081/eureka
启动类:
package com.zsy.cloud.cloud_ribbon;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.web.client.RestTemplate;@SpringBootApplication@EnableDiscoveryClientpublic class RibbonApp { public static void main(String[] args) { SpringApplication.run(RibbonApp.class, args); } @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); }}
Controller类:
package com.zsy.cloud.cloud_ribbon.controller;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.cloud.client.loadbalancer.LoadBalanced;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import com.zsy.cloud.cloud_ribbon.service.TestService;@Controllerpublic class TestController { @Autowired private TestService testService; @GetMapping("/hello") @LoadBalanced public String test(String name) { return testService.test(name); }}
Service类:
package com.zsy.cloud.cloud_ribbon.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.web.client.RestTemplate;@Servicepublic class TestService { @Autowired private RestTemplate template; public String test(String name) { return template.getForObject("http://eureka-client/test?name="+name, String.class); }}
启动注册中心,测试站点(4个,不同端口),效果图如下:
访问controller路径:
转载地址:http://fvbai.baihongyu.com/