本文将介绍如何使用Ribbon访问注册到eureka中的另外一个服务。ribbon可以代替部分feign的作用,其关键是rest+json。
1、环境约束
- win10 64为操作系统
- idea2018.1.5
- maven-3.0.5
- jdk-8u162-windows-x64
2、前提约束
- 已经创建好一个注册中心并已启动 https://www.jianshu.com/p/0c4ac4b0c128
假设该注册中心端口为7561 - 已经在注册中心上注册了一个服务 https://www.jianshu.com/p/b730990d1daf
假设已经注册的服务名称为provider-service
3、操作步骤
- 创建一个springcloud项目,包括springweb、eureka client、ribbon模块,关键依赖如下:
<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>
注意:springboot的版本是2.1.4.RELEASE,springcloud的版本是Greenwich.SR1
- 设置application.properties
server.port=8002
eureka.client.service-url.defaultZone=http://localhost:7561/eureka/
- 在主启动类同级目录以下,创建RestConfig.java
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
@Bean
public IRule getRule(){
return new RandomRule();
}
}
- 在主启动类同级目录下,创建ConsumerController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consumer")
public String consumer(){
String url = "http://provider-service";
//注意,String.class是提供者方法的返回类型,作者的provider-service中的/query接口返回类型就是String,请读者根据自己实际的提供者确定
return restTemplate.getForObject(url+"/query",String.class);
}
}
- 打开浏览器,输入http://localhost:8002/consumer,便能看到provider-service【8001端口】提供的返回结果。