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);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Eureke Eureka是Netflix开源的一款提供服务注册和发现的产品,它提供了完整的Service Reg...
    fad2aa506f5e阅读 3,328评论 0 0
  • 第一点:今天找个三个朋友聊聊生活,孩子,工作的事,为谈产品做铺垫,不想一下子就带有目的性的去聊天,这样聊会把朋友聊...
    微微_4793阅读 1,241评论 0 0
  • 在感情过程中我们都是这么的懵懂,对于另一半并没有全面的了解,而且很容易在对方蜜汁细雨中迷失自我,时常保持清...
    冰孤子阅读 1,345评论 0 3
  • 我不怕一个人走在黑暗里,怕的是心中再没有光 —— 一凡 总会听到有人说,遇到那么多人还是初恋最好,忘记那么多事,却...
    至此一生_阅读 1,729评论 0 1
  • 我的孩子们!我憧憬于你们的生活,每天不止一次!我想委屈地说出来,使你们自己晓得。可惜到你们懂得我的话的意思的时候,...
    Estelle_wwt阅读 2,338评论 0 0