SpringCloud学习笔记(4)————Ribbon

  1. ribbon是一个基于http 和tcp客户端的负载均衡器,联合eureka时,重写ribbonServerList,扩展从eureka注册中心获取服务端列表。
  2. 新建module:service-ribbon,修改pom.xml。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
       <groupId>com.springcloud</groupId>
       <artifactId>eureka</artifactId>
       <version>1.0-SNAPSHOT</version>
   </parent>
   <groupId>com.springcloud</groupId>
   <artifactId>service-ribbon</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>service-ribbon</name>
   <dependencies>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
       </dependency>
   </dependencies>
</project>
  1. 修改appliction.yml
spring:
  application:
    name: service-ribbon
server:
  port: 8764
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  1. 在启动类中添加@EnableEurekaClient,@EnableDiscoveryClient,并向程序中注入bean:restTemplate,通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceRibbonApplication {

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

	@Bean
	@LoadBalanced
	RestTemplate restTemplate(){
		return new RestTemplate();
	}

}
  1. 编写一个service来消费创建好的“eureka-client”(参照服务的发现),EUREKA-CLIENT为以前配置的名称,链接可以用程序名代替具体的url
@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    public String hiService(String name) {
        return restTemplate.getForObject("http://EUREKA-CLIENT/test?name=" + name, String.class);
    }
}
  1. 写一个controller,在controller中用调用HelloService 的方法
@RestController
public class HelloController {
    @Autowired
    HelloService helloService;

    @GetMapping("/hi")
    public String hi(@RequestParam String name) {
        return helloService.hiService(name);
    }
}
  1. 修改eureka-client的配置(如下图),以8762端口启动一次,改端口为8763再次启动,之后会出现两个服务。
    7-1
    图7-2
    7-3
  2. 启动service-ribbon,访问接口,端口会在8672与8763轮询,以实现负载均衡。
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值