Spring Cloud - 服务消费者Ribbon

169 阅读1分钟

概述

在微服务架构中,业务被拆分为一个个服务,各服务间通过http restful进行通信。Spring Cloud有两种服务调用方式,一种是ribbon + restTemplate,另一种是feign。

创建服务集群

创建两个eureka-hi工程,两者的不同在于启动端口不一样,一个为1002,一个为1003,其余的都一样。

spring.application.name=eureka-hi
server.port=1002/1003
eureka.client.service-url.defaultZone=http://localhost:1000/eureka/

创建ribbon

在application类添加@EnableDiscoveryClient注解并注入restTemplate bean

package com.whut.springcloud.eurekaribbon;

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.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient  // 添加@EnableDiscoveryClient,向服务注册中心注册
public class EurekaRibbonApplication {

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

	/**
	 *注入restTemplate bean
	 * @LoadBalanced注解:表明restTemplate开启负载均衡功能
	 */
	@Bean
	@LoadBalanced
	RestTemplate restTemplate(){
		return new RestTemplate();
	}
}

编写配置文件

spring.application.name=eureka-ribbon
server.port=1004
eureka.client.service-url.defaultZone=http://localhost:1000/eureka/

服务负载均衡测试

  • 编写serveice类
package com.whut.springcloud.eurekaribbon.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * User:  Chunguang Li
 * Date:  2018/3/10
 * Email: 1192126986@foxmail.com
 */

@Service
public class RibbonService {
    @Autowired
    private RestTemplate restTemplate;

    public String hiService(String name){
        // 调用EUREKA-HI服务提供的"/hi"方法接口
        return restTemplate.getForObject("http://EUREKA-HI/hi?name=" + name, String.class);
    }
}

  • 编写controller类
@RestController
public class HiController {
    @Autowired
    private RibbonService ribbonService;

    @GetMapping("/ribbon")
    public String ribbonController(@RequestParam("name")String name){
        return ribbonService.hiService(name);
    }
}

工作流程

  • 一个服务注册中心 - eureka-server:1000
  • 两个服务提供者 - eureka-hi:1002 eureka-hi:1003,分别向服务注册中心注册
  • 一个负载均衡器 - eureka-ribbon:1004,向服务注册中心注册
  • eureka-ribbon通过restTemplate调用eureka-hi的/hi接口时,因为restTemplate做了负载均衡,所以会轮流调用eureka-hi:1002/1003的/hi接口