创建服务消费者(Ribbon)

概述

在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于 http restful 的。Spring cloud 有两种服务调用方式,一种是 ribbon + restTemplate,另一种是 feign。在这一篇文章首先讲解下基于 ribbon + rest。

Ribbon简介

Ribbon 是一个负载均衡客户端,可以很好的控制 http 和 tcp 的一些行为。

准备工作

  • 启动服务提供者

  • 启动Eureka注册中心

创建服务消费者(POM)


       <!--spring cloud starter ribbon-->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-ribbon</artifactId>
       </dependency>
       
<!--spring cloud starter eureka-->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-eureka</artifactId>
       </dependency>

       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

Application


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 EurekaRibbonClientApplication {

   //使用注解@LoadBalanced标记RestTemplate
   @Bean
   @LoadBalanced
   public RestTemplate restTemplate() {
       return new RestTemplate();
  }

   public static void main(String[] args) {
       SpringApplication.run(EurekaRibbonClientApplication.class, args);
  }
}

application.yml

server:
port: 9002

spring:
application:
  name: eureka-client-ribbon

eureka:
client:
  serviceUrl:
    defaultZone: http://localhost:1111/eureka/
instance:
  lease-renewal-interval-in-seconds: 10 #服务续约
  lease-expiration-duration-in-seconds: 15 #服务剔除>服务续约时间

创建测试的Controller


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;

@RestController
@RequestMapping("/api")
@Slf4j
public class RibbonController {

   @Autowired
   private RestTemplate restTemplate;
   
   //loadbalanced客户端
   @Autowired
   private LoadBalancerClient loadBalancerClient;


   @GetMapping("/ribbon/hello")
   public String hello() {
       String result = restTemplate.getForObject("http://eureka-provider/hello",String.class);
       return result;
  }
}

在IDEA中配置一个工厂启动多个实例

步骤一

点击 Run -> Edit Configurations...

#步骤二

选择需要启动多实例的项目并去掉 Single instance only 前面的勾

#步骤三

通过修改 application.yml 配置文件的 server.port 的端口,启动多个实例,需要多个端口,分别进行启动即可。

原文地址:https://www.cnblogs.com/liuenyuan1996/p/10288060.html