一、部分组件
eureka(服务注册)、ribbon(负载均衡器)、feign(服务调用)、hystrix(断路器)...
dubbo远程通讯协议:RPC
springcloud远程通讯协议:HTTP (HTTP RESTful)
二、版本
三、组件使用介绍
1:eureka
pom:
yml:
# server端口号
server:
port: 9000
#防止自己注册自己,所以将值改为false
eureka:
client:
register-with-eureka: false #单机版建议设置成false,防止注册自己,集群版默认采用ture
fetch-registry: false #单机版建议设置成false,防止自己发现自己,集群版默认采用ture
#注册中心的地址(注意:地址最后面的 /eureka/ 这个是固定值),集群多个服务使用逗号隔开
serviceUrl:
defaultZone: http://localhost:${server.port}/eureka/
spring:
application:
name: spring-cloud-server #应用名
1):不要使用ip+port的方式访问,取而代之的是应用名
2):这种方式发送的请求都会被ribbon拦截,ribbon从eureka注册中心获取服务列表,然后采用均衡策略进行访问。
为什么加上@LoadBalanced注解,就能均衡访问集群呢?
这里面的功劳归根ribbon组件,当我们应用依赖了eureka-client的时候,eureka-client依赖了ribbon,虽然看是ribbon没有存在感,但是ribbon默默的发挥着自己的负载均衡能力。
发布公网中安全考录使用账户密码:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-securityartifactId>
dependency>
yml:
spring:
profiles: discovery1 #注册中心1
security:
user:
name: admin
password: 123456
server:
port: 8761
eureka:
instance:
hostname: discovery1
client:
serviceUrl:
defaultZone: http://admin:123456@localhost:8762/eureka,http://admin:123456@localhost:8763/eureka
2:ribbon
1):user微服务1、user微服务2、user微服务3是一个服务集群,它们都会向注册中心注册服务(它们的应用名都是USER-SERVICE)
2):注册中心记录集群元数据信息,即USER-SERVICE下有3个服务节点
3):Ribbon拦截所有的请求,从请求信息中获取应用名
4):ribbon根据应用名从eureka注册中心获取服务列表
5):ribbon从服务列表中通过相关均衡策略获取具体某个服务
6):请求远程服务
源码执行顺序:
1)、Ribbon拦截请求,获取应用名
2)、通过应用名获取服务列表,
3)、默认均衡策略ZoneAvoidanceRule,在RibbonClientConfiguration配置类中配置了IRule bean
自定义负载均衡器:
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.wendao.api"})
public class UserCenterApplication {
public static void main(String[] args) {
SpringApplication.run(UserCenterApplication.class,args);
}
// @Bean
// @LoadBalanced //使用负载均衡器Ribbon
// public RestTemplate getRestTemplate(){
// return new RestTemplate();
// }
// @Bean
// public IRule myRule(){
// return new RetryRule(); 重试
// return new RoundRobinRule(); 轮训
// return new RandomRule(); 随机
// return new WeightedResponseTimeRule(); 权重
// return new BestAvailableRule(); 线性(取并发最小的服务)
// }
3:feign
pom
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
@RequestMapping(value = "/course")
public interface ICourseService {
@RequestMapping(value = "/user/{uesrId}")
User findUserById(@PathVariable("uesrId") Integer userId);//Feign使用需严格要求注解的使用规范
}
hystrix
feign.hystrix.enabled=true