SpringCloud之Ribbon的使用
个人记录学习
一、准备工作
1.修改服务消费方pom文件
<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;
@SpringBootApplication
@EnableDiscoveryClient
public class EuerkaConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(EuerkaConsumerApplication.class);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
3.编写服务提供方方法
1.服务方代码
@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;
@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. 调用消费方接口
|