spring ribbon 简单用例

1. ribbon是什么?

负载均衡器,跟eureka-server,eureka-client配合,可实现服务访问的负载均衡。比如,有2台机器发布了服务a,服务b机器通过ribbon消费服务a时,请求会均分到2台发布服务a的机器上。

2. jar包依赖

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
        dependency>
         
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-netflix-ribbonartifactId>
        dependency>

3. application.yml 配置

spring:
  application:
    #应用名称
    name: app-b
eureka:
  instance:
    #服务签订间隔
    lease-renewal-interval-in-seconds: 5
    #签订成功到期时间
    lease-expiration-duration-in-seconds: 10
    #自定义应用标识
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    #开启ip地址显示
    prefer-ip-address: true
  client:
    service-url:
       #eureka服务地址
       defaultZone: http://localhost:8761/eureka/
server:
  #应用端口
  port: 9091

4. Application.java 代码

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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
@EnableEurekaClient
public class Application {

    @Bean
    @LoadBalanced //加载负载均衡配置
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

5. 测试demo

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

@RestController
public class TestController {

    @Autowired
    private RestTemplate template;

    @GetMapping("test")
    public String test() {
        //app-a 为注册在eureka-server中的a服务名称,info为提供的服务地址
        return template.getForObject("http://app-a/info", String.class);
    }
}

6. 简单项目demo地址

https://github.com/wangdie0623/ribbon-demo

你可能感兴趣的:(spring-cloud,ribbon)