一、ribbon简介
Ribbon is a client side load balancer which gives you a lot of control over the behaviour of HTTP and TCP clients. Feign already uses Ribbon, so if you are using @FeignClient then this section also applies.
—–摘自官网
ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。
ribbon 已经默认实现了这些配置bean:
IClientConfig ribbonClientConfig: DefaultClientConfigImpl
IRule ribbonRule: ZoneAvoidanceRule
IPing ribbonPing: NoOpPing
ServerList ribbonServerList: ConfigurationBasedServerList
ServerListFilter ribbonServerListFilter: ZonePreferenceServerListFilter
ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalancer
二、准备工作
这一篇文章基于上一篇文章的工程,启动eureka-server 工程;启动service-hi工程,它的端口为8762;将service-hi的配置文件的端口改为8763,并启动,这时你会发现:service-hi在eureka-server注册了2个实例,这就相当于一个小的集群。访问localhost:8761如图所示:
三、建一个服务消费者
重新新建一个spring-boot工程,取名为:service-ribbon;
在它的pom.xml文件分别引入起步依赖spring-cloud-starter-eureka、spring-cloud-starter-ribbon、spring-boot-starter-web,代码如下:复制代码 4.0.0 com.forezp service-hi 0.0.1-SNAPSHOT jar service-hi Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 1.5.2.RELEASE UTF-8 UTF-8 1.8 org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-dependencies Dalston.RC1 pom import org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone false
通过注解@EnableEurekaClient 表明自己是一个eurekaclient.
@SpringBootApplication@EnableEurekaClient@RestControllerpublic class ServiceHiApplication { public static void main(String[] args) { SpringApplication.run(ServiceHiApplication.class, args); } @Value("${server.port}") String port; @RequestMapping("/hi") public String home(@RequestParam String name) { return "hi "+name+",i am from port:" +port; } }复制代码
仅仅@EnableEurekaClient是不够的,还需要在配置文件中注明自己的服务注册中心的地址,application.yml配置文件如下:
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/server: port: 8762spring: application: name: service-hi复制代码
需要指明spring.application.name,这个很重要,这在以后的服务与服务之间相互调用一般都是根据这个name 。
启动工程,打开 ,即eureka server 的网址:你会发现一个服务已经注册在服务中了,服务名为SERVICE-HI ,端口为7862
这时打开 ,你会在浏览器上看到 :
hi forezp,i am from port:8762复制代码
架构代码如下:
Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码请加企鹅求求:一零三八七七四六二六