SpringCloud之Ribbon的使用
个人记录学习
文章目录
一、准备工作
1.修改服务消费方pom文件
<!-- 添加ribbon依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
2. 修改服务消费启动类
package com.yun;
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;
/**
* @author kaka
* @description consumer
* @date 2022-07-11 13:26
*/
@SpringBootApplication
@EnableDiscoveryClient //当前使用eureka的server
public class EuerkaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(EuerkaConsumerApplication.class);
}
//注入RestTemplate ,使用 @LoadBalanced注解(Ribbon负载均衡,默认轮换)
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
3.编写服务提供方方法
1.服务方代码
/**
* @description:获取调用的地址
* @author: kaka
* @date: 2022-07-12 17:35:51
* @param
* @return java.lang.String
*/
@RequestMapping("/yettl")
public String yettl(){
ServiceInstance serviceInstance =loadBalancerClient.choose("EUREKA-SERVICE");
return serviceInstance.getServiceId()+serviceInstance.getHost()+serviceInstance.getPort();
}
2. 消费方调用
package com.yun;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author kaka
* @description \
* @date 2022-07-11 13:28
*/
@RestController
@RequestMapping("/Hello")
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/tengman")
public String tengman(){
String froObject = restTemplate.getForObject("http://EUREKA-SERVICE/hello/yettl",String.class);
return froObject;
}
}
4.配置多个服务提供方
完成后将一个注册中心,两个服务提供方,一个服务消费方全部启动起来。
5. 进行测试
1. 启动后可以看到注册中心有两个服务提供方(说明刚才的配置已经成功)
2. 调用消费方接口