本文主要是介绍Spring Cloud(二) Ribbon 客户端负载均衡,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本章基于上一章的例子来的
1.maven依赖
...
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.3.RELEASE</version><relativePath/> <!-- lookup parent from repository -->
</parent>
...
<properties><java.version>1.8</java.version><spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
...
<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>
</dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>...
这里之所以没添加spring-cloud-starter-netflix-ribbon,那是因为在spring-cloud-starter-netflix-eureka-client包中已经包含此包
eureka注册中心
2.application.yml配置
server:port: 7020spring:application:name: ribbon-clienteureka:instance:instance-id: ${spring.application.name}:${spring.cloud.client.hostname}:${server.port}status-page-url: http://${spring.cloud.client.hostname}:${server.port}/democlient:register-with-eureka: true #由于该应用为注册中心,所以设置为false,代表不向注册中心注册自己fetch-registry: true #检索服务列表service-url:defaultZone: http://peer1:7001/eureka/
3.调用接口服务
@RestController
public class RibbonDemoController {@Autowiredprivate RestTemplate restTemplate;@GetMapping("demo")public String demo() {String params = "ribbon调用";
// String res = restTemplate.getForObject("http://eureka-client/demo?params="+params, String.class);Map<String,Object> variable = new HashMap<String, Object>();variable.put("params", params);String res = restTemplate.getForObject("http://eureka-client/demo?params={params}", String.class, variable);return res;}
}
4.启动类
@SpringBootApplication
@EnableEurekaClient
public class SpringcloudRibbonApplication {public static void main(String[] args) {SpringApplication.run(SpringcloudRibbonApplication.class, args);}@Bean@LoadBalancedRestTemplate restTemplate() {return new RestTemplate();}
}
5.调用结果
这篇关于Spring Cloud(二) Ribbon 客户端负载均衡的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!