为了巩固自身学习,从今天(2019.01.08),天天晚上开始总结SpringCloud的相关学习,用于自我勉励,自我积累与人生总结。html
总结2018年的我,心态较之从前浮躁,杂念多了,没有用心,更没能好好的反思本身;按照本身单身的状况,平时我本应该有更多的时间去学习,去提升,去真正的充实本身。java
学习自己就并不是易事,不管是为了生活仍是理想,仍是一种生活状态,最重要的是要用心,要真正的去理解,更要沉得住气,静得下心。git
选择了IT这一行,应该有苦修的觉悟,任何技术只停留在简单会用的阶段(目前我深陷其中),实际上是远远不够的。就跟我最先学了spring-cloud-ribbon只知道一个**@LoadBalanced**同样,感受很空洞,遇到问题可能就会一筹莫展,由于本身根本没有真正的学会一件事,没有真正悟到它的原理,认清它的本质。github
2019年,我但愿我能戒掉周末还有时间打游戏的生活状态,能充实本身,克服焦虑;web
2019年,我但愿我能坚持,能勤奋;spring
2019年,我但愿我能多读书,能成长;bootstrap
2019年,我但愿我能坦然面对生活中的任何压力,能有内驱动力,能找到女友,找到外驱动力。缓存
但愿我每次看到这段给本身的话,都不要忘了初心。安全
好了,闲言碎语,皆尽于此。服务器
它主要记录各个微服务和微服务地址的映射关系,各个微服务都将本身注册到这个注册中心上面,当微服务之间须要互相调用时,就能够从注册中心上面去发现微服务和进行调用。
Spring Cloud是一个开箱即用的微服务框架,秉承了微服务的真正理念而设计。
注 : 本文只讲Eureka,不关注Consul与Zookeeper等替代方案
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-eureka-server</artifactId>
</dependency>
复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/** * Created by EalenXie on 2018/12/28 14:13. */
@EnableEurekaServer
@SpringBootApplication
public class SpringCloudEurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaServerApplication.class, args);
}
}
复制代码
server:
port: 8761
eureka:
instance:
hostname: localhost # 服务注册中心实例的主机名
lease-renewal-interval-in-seconds: 30 # 客户端向Eureka发送心跳周期(s)
lease-expiration-duration-in-seconds: 90 # Eureka Server接收实例的最后一次发出的心跳后,删除须要等待时间(s)
server:
enable-self-preservation: true # Eureka自我保护模式
client:
register-with-eureka: false # 是否向服务注册中心注册本身
fetch-registry: false # 是否检索发现服务
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # 指定服务注册中心的位置
复制代码
Eureka Server 实例1 配置
server:
port: 8761
eureka:
instance:
hostname: localhost # 服务注册中心实例的主机名
server:
enable-self-preservation: true # Eureka自我保护模式
client:
register-with-eureka: true # 是否注册到Eureka Server
fetch-registry: true # 是否检索发现服务
service-url:
defaultZone: http://${eureka.instance.hostname}:8762/eureka/,http://${eureka.instance.hostname}:8763/eureka/
#指定多个服务注册中心的位置,并向服务注册中心注册本身
复制代码
Eureka Server 实例2 配置
server:
port: 8762
eureka:
instance:
hostname: localhost # 服务注册中心实例的主机名
server:
enable-self-preservation: true # Eureka自我保护模式
client:
register-with-eureka: true # 是否注册到Eureka Server
fetch-registry: true # 是否检索发现服务
service-url:
defaultZone: http://${eureka.instance.hostname}:8761/eureka/,http://${eureka.instance.hostname}:8763/eureka/
#指定多个服务注册中心的位置,并向服务注册中心注册本身
复制代码
...
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/** * Created by EalenXie on 2018/12/28 14:45. */
@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudEurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaClientApplication.class, args);
}
}
复制代码
server:
port: 8090
spring:
application:
name: spring-cloud-eureka-client-application
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
复制代码
package com.netflix.discovery.shared;
import java.util.List;
import com.netflix.appinfo.InstanceInfo;
public interface LookupService<T> {
Application getApplication(String appName);
Applications getApplications();
List<InstanceInfo> getInstancesById(String id);
InstanceInfo getNextServerFromEureka(String virtualHostname, boolean secure);
}
复制代码
默认状况下,若是Eureka Server在必定时间内没有接收到某个微服务实例的心跳,Eureka Server将会注销该实例(默认90秒)。
可是当网络分区故障发生时,会统计心跳失败的比例,阈值因子默认是0.85,若是阈值比最小值大则代表微服务与Eureka Server之间没法正常通讯,这就可能变得很是危险了--由于微服务自己是健康的,此时本不该该注销这个微服务。
Eureka Server经过'自我保护模式'来解决这个问题,当Eureka Server节点在短期内丢失过多客户端时(可能发生了网络分区故障),那么这个节点就会进入自我保护模式。
一旦进入该模式,Eureka Server就会保护服务注册表中的信息,再也不删除服务注册表中的数据(也就是不会注销任何微服务)。当网络故障恢复后,该Eureka Server节点会自动退出自我保护模式。
自我保护模式是一种对网络异常的安全保护措施。使用自我保护模式,而已让Eureka集群更加的健壮、稳定。
复制代码
POST /eureka/apps/{appId} 注册新的实例
DELETE /eureka/apps/{appId}/{instanceId} 注销应用实例
PUT /eureka/apps/{appId}/{instanceId} 应用实例发送心跳
GET /eureka/apps 查询全部的实例
GET /eureka/apps/{appId} 查询指定appId的实例
GET /eureka/apps/{appId}/{instanceId} 查询指定appId和instanceId的实例
GET /eureka/instances/{instanceId} 查询指定的instanceId的实例
PUT /eureka/apps/{appId}/{instanceId}/status?value=OUT_OF_SERVICE 暂停应用实例
PUT /eureka/apps/{appId}/{instanceId}/status?value=UP 恢复应用实例
PUT /eureka/apps/{appId}/{instanceId}/metadata?key=value 更新元数据信息
GET /eureka/vips/{vipAddress} 根据vip地址查询
GET /eureka/svips/{svipAddress} 根据svip地址查询
复制代码
InstanceInfo : 注册的服务实例,里面包含服务实例的各项属性
LeaseInfo : Eureka用这个类来标识应用实例的租约信息
ServiceInstance : 发现的实例信息的抽象接口,约定了服务发现的实例应用有哪些通用信息
InstanceStatus : 用于标识服务实例的状态,是一个枚举类,主要有状态UP,DOWN,STARTING,OUT_OF_SERVICE,UNKNOWN
EurekaServerConfigBean : Eureka Server的核心配置类,里面包含了Eureka Server的各项核心属性信息
复制代码
package com.netflix.eureka.lease;
import com.netflix.eureka.registry.AbstractInstanceRegistry;
public interface LeaseManager<T> {
void register(T r, int leaseDuration, boolean isReplication);
boolean cancel(String appName, String id, boolean isReplication);
boolean renew(String appName, String id, boolean isReplication);
void evict();
}
复制代码
服务注册(register) : 其余客户端将本身注册到Eureka上面
服务下线(cancel) : Eureka 删除服务信息
服务租约(renew) : 客户端定时向Eureka发送心跳证实本身存活,Eureka接收到心跳为其维持租约
服务剔除(evict) : Eureka Server的方法,剔除心跳检测过时的服务实例
复制代码
package name.ealen.listener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.eureka.server.EurekaServerConfigBean;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/** * Created by EalenXie on 2018/9/20 14:46. * EurekaServerEventListener 监听Eureka的事件行为 * 注 : EurekaInstanceRegisteredEvent,EurekaInstanceCanceledEvent,EurekaInstanceRenewedEvent */
@Component
public class EurekaServerEventListener {
private static final Logger log = LoggerFactory.getLogger(EurekaServerEventListener.class);
/** * Eureka Server 注册事件 */
@EventListener
public void eurekaRegister(EurekaRegistryAvailableEvent event) {
//write your logic..........
log.info("Eureka Server Register at timestamp : {}", event.getTimestamp());
}
/** * Eureka Server 启动事件 */
@EventListener
public void serverStart(EurekaServerStartedEvent event) {
//write your logic..........
Object source = event.getSource();
if (source instanceof EurekaServerConfigBean) {
EurekaServerConfigBean eureka = (EurekaServerConfigBean) source;
log.info("Eureka ServerConfigBean : {}",eureka);
}
}
/** * 服务注册事件 */
@EventListener(condition = "#event.replication==false")
public void instanceRegister(EurekaInstanceRegisteredEvent event) {
//write your logic..........
log.info("Register InstanceInfo : {}",event.getInstanceInfo());
}
/** * 服务下线事件 */
@EventListener(condition = "#event.replication==false")
public void instanceCancel(EurekaInstanceCanceledEvent event) {
//write your logic..........
log.info("instanceCancel serviceId : {}",event.getServerId());
}
/** * 服务续约事件 */
@EventListener(condition = "#event.replication==false")
public void instanceRenewed(EurekaInstanceRenewedEvent event) {
//write your logic..........
}
}
复制代码
Eureka会为每一个核心动做发布一个相关的事件,咱们能够经过监听这些事件来作一些针对性的自定义处理逻辑。
Eureka Server自身注册事件 : EurekaRegistryAvailableEvent
Eureka Server自身启动事件 : EurekaServerStartedEvent
服务注册事件(register) : EurekaInstanceRegisteredEvent
服务下线事件(cancel) : EurekaInstanceCanceledEvent
服务租约事件(renew,续约,发送心跳) : EurekaInstanceRenewedEvent
复制代码
Spring Boot Actuator 提供了/health 端点
只须要启用Eureka的健康检查,就能够将端点中的健康状态传递到Eureka Server
eureka.client.healthcheck.enable: true
注意 : 这个只能在application.yml中配置,若是在bootstrap.yml中配置,可能会致使一些不良后果。
这一点官方有明确说明 : cloud.spring.io/spring-clou…
eureka.client.register-with-eureka: true 是否注册本身到Eureka Server上面
eureka.client.fetch-registry: true 是否从Eureka Server上面拉取服务信息
eureka.client.enable: true 是否启用Eureka客户端,不启用则不注册到Eureka Server
eureka.client.healthcheck.enable: true 是否启用Eureka健康检查
eureka.client.availability-zones: new HashMap<>() 告诉client有哪些可用的region和zone
eureka.client.filter-only-up-instances: true 是否过滤出InstanceStatus为UP的实例
eureka.client.region: us-east-1 指定该应用实例所在的region,AWS datacenters适用
eureka.client.prefer-same-zone-eureka: true 是否优先使用与该应用相同Zone的Eureka Server
eureka.client.cache-refresh-executor-thread-pool-size: 2 缓存刷新线程池CacheRefreshThread的初始化线程数
eureka.client.registry-fetch-interval-seconds: 30 Eureka client拉取服务注册信息间隔时间(s)
eureka.client.instance-info-replication-interval-seconds: 30 复制实例变化信息到Eureka服务器所须要的时间间隔(s)
eureka.client.eureka-service-url-poll-interval-seconds: 300 轮询Eureka服务端地址更改的间隔时间(s)
eureka.client.eureka-server-read-timeout-seconds: 8 读取Eureka Server信息的超时时间(s)
eureka.client.eureka-server-connect-timeout-seconds: 5 链接Eureka Server的超时时间(s)
eureka.client.eureka-server-total-connections: 200 从Eureka客户端到全部Eureka服务端的链接总数
eureka.client.eureka-server-total-connections-per-host: 50 从Eureka客户端到每一个Eureka服务端主机的链接总数
eureka.client.eureka-connection-idle-timeout-seconds: 30 Eureka服务端链接的空闲关闭时间(s)
eureka.instance.metadata-map: new HashMap<>() 指定应用实例的元数据信息
eureka.instance.prefer-ip-address: false 是否优先使用ip地址来替代hostname做为实例hostname字段值
eureka.instance.lease-expiration-duration-in-seconds: 90 Eureka clent最后一次心跳后,Eureka Server剔除须要等待时间(s)
eureka.instance.lease-renewal-interval-in-seconds: 30 客户端向Eureka Server发送心跳周期(s)
复制代码
eureka.server.enable-self-preservation: true Eureka Server是否开启自我保护模式
eureka.server.renewal-percent-threshold: 0.85 指定每分钟须要收到的续约次数的阙值,若是阈值比最小值大,则自我保护模式开启
eureka.server.eviction-interval-timer-in-ms: 60*1000 指定EvictionTask定时任务的调度频率,用于剔除过时的实例
eureka.server.wait-time-in-ms-when-sync-empty: 1000*60*5 在Eureka服务器获取不到集群里对等服务器上的实例时,须要等待的时间
复制代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
复制代码
security:
basic:
enabled: true # 开启基于HTTP Basic的认证
user:
name: ealenxie # 登录帐号名
password: zaxscdvfrewq # 登录密码
server:
port: 8761
eureka:
instance:
hostname: localhost # 服务注册中心实例的主机名
client:
register-with-eureka: false # 是否向服务注册中心注册本身
fetch-registry: false # 是否检索发现服务
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ # 指定服务注册中心的位置
复制代码
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
public class EurekaServerSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf().disable();
}
}
复制代码
security:
basic:
enabled: true # 开启基于HTTP Basic的认证
user:
name: ealenxie # 登录帐号名
password: zaxscdvfrewq # 登录密码
server:
port: 8090
spring:
application:
name: spring-cloud-eureka-client-application
eureka:
client:
service-url:
defaultZone: http://${security.user}:${security.password}@localhost:8761/eureka/ #包含帐号信息的Eureka Server地址
复制代码
其实现方式能够参考博客(篇幅缘由) : www.v2ex.com/t/516287
或者参考《从新定义Spring Cloud实战》一书 , 61页章节,启用https。
基本效果 :
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>spring-boot-admin-server-ui</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 在管理界面中与 JMX-beans 进行交互所须要被依赖的 JAR -->
<dependency>
<groupId>org.jolokia</groupId>
<artifactId>jolokia-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
复制代码
package name.ealen;
import de.codecentric.boot.admin.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/** * Created by EalenXie on 2018/11/6 9:23. */
@SpringBootApplication
@EnableDiscoveryClient
@EnableAdminServer
public class SpringBootAdminApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootAdminApplication.class,args);
}
}
复制代码
server:
port: 8889
spring:
application:
name: spring-cloud-boot-admin
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
management:
security:
enabled: false
复制代码
点开 Details按钮,能够看到Admin里面的各类详细配置信息,内存信息,接口调用次数,甚至是线程数量,均可以一目了然,十分方便。
大量参考了《从新定义Spring Cloud实战》一书的内容 , 我的十分推崇。
参考了周立老师的《Spring Cloud与Docker》一书。
参考了翟永超大神的《Spring Cloud 微服务实战》一书。
本文是总结根据自身从各路大神所学习到的内容与理解。
我的才疏学浅,如博文有不当之处,望各路大神见谅和帮忙指正。
原创不易,十分感谢各位提出意见和支持。