04 使用Ribbon访问注册到eureka的服务

本文将介绍如何使用Ribbon访问注册到eureka中的另外一个服务。ribbon可以代替部分feign的作用,其关键是rest+json。

1、环境约束

  • win10 64为操作系统
  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64

2、前提约束

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值