美文网首页
SpringCloud Eureka 使用Ribbon

SpringCloud Eureka 使用Ribbon

作者: AllSun | 来源:发表于2018-04-18 14:17 被阅读0次

服务消费者

在上一遍文章中,我们构建了注册中心和服务提供者,有服务,就要有消费服务的关系,这次我们搭建基于Ribbon的服务消费者。

Ribbon

Ribbon是一个基于HTTP和TCP客户端的负载均衡器。

Ribbon可以在通过客户端中配置的ribbonServerList服务端列表去轮询访问以达到均衡负载的作用。

当Ribbon与Eureka联合使用时,ribbonServerList会被DiscoveryEnabledNIWSServerList重写,扩展成从Eureka注册中心中获取服务端列表。同时它也会用NIWSDiscoveryPing来取代IPing,它将职责委托给Eureka来确定服务端是否已经启动。

新建项目

新建一个项目test-consumer

添加依赖pom.xml

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

主类中添加注解

在应用主类中,通过@EnableDiscoveryClient注解来添加发现服务能力。创建RestTemplate实例,并通过@LoadBalanced注解开启均衡负载能力。

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;

@EnableDiscoveryClient
@SpringBootApplication
public class TestConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestConsumerApplication.class, args);
    }
    
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

创建Controller层,来消费service层的服务

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class HelloController {
    @Autowired
    RestTemplate restTemplate;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return restTemplate.getForEntity("http://test-service/add?a=1&b=3", String.class).getBody();
    }

}

创建配置文件

spring:
  application:
    name: test-consumer   #消费者的程序名称
server:
  port: 2222              #本程序的端口
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:1111/eureka/   #注册中心的地址

启动程序

先启动 注册中心 test-reg

再启动 服务提供者 test-service

在建一个服务提供者 其他都一样,改下端口配置

最后启动 服务消费者 test-consumer

输入http://localhost:1111/ 查看两个服务已经注册

输入消费者的地址http://localhost:2222/hello输出4

这样就实现了负载均衡,Ribbon会轮询访问服务实例,关掉其中一个实例,会自动去寻找下一个。

相关文章

网友评论

      本文标题:SpringCloud Eureka 使用Ribbon

      本文链接:https://www.haomeiwen.com/subject/owmvkftx.html