SpringCloud(二)笔记之Eureka
Eureka包含两个组件:Eureka Server和Eureka Client
Eureka Server:提供服务注册服务,各个节点启动后,会在Eureka Server中进行注册
Eureka Client:应用启动后,将会向Eureka Server发送心跳,默认周期为30秒,如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,Eureka Server将会从服务注册表中把这个服务节点移除(默认90秒)
一、构建Eureka Server
mhb-cloud-eureka【端口:8761】
mhb-cloud-eureka2【端口:8762】
mhb-cloud-eureka3【端口:8763】
1:pom文件(加入Eureka-server依赖)
<!--eureka服务环境支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--eureka服务安全控制-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2:application.yml文件
集群中三台的配置文件,以下三处不同:
#服务名称不同
spring:
application:
name: mhb-cloud-eureka #每一个微服务必须有这个应用名称
#服务端口不同
server:
port: 8761 #服务端口
#服务主机不同
eureka:
instance:
hostname: eureka1.com #eureka服务的主机 hosts文件映射了
spring:
application:
name: mhb-cloud-eureka #每一个微服务必须有这个应用名称
security: #eureka验证信息
user:
name: admin
password: 123456
server:
port: 8761 #服务端口
eureka:
instance:
hostname: eureka1.com #eureka服务的主机 hosts文件映射了
server:
enable-self-preservation: false #关闭自我保护模式 生产环境不建议关闭
eviction-interval-timer-in-ms: 2000 #间隔2秒剔除
client:
## 是否注册自身到eureka服务器
register-with-eureka: false
## 因为自己是注册中心,不需要去检索服务信息
fetch-registry: false
service-url: #单机版不需要配置此属性
#集群配置
defaultZone: http://admin:123456@eureka2.com:8762/eureka/,http://admin:123456@eureka3.com:8763/eureka/
3:在启动类上开启Eureka注解
@EnableEurekaServer
package com.applesnt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer/*eureka注解*/
public class MhbCloudEurekaApplication {
public static void main(String[] args) {
SpringApplication.run(MhbCloudEurekaApplication.class, args);
}
}
4:开启Eureka安全认证
com\applesnt\config\CsrfSecurityConfig.java
@@EnableWebSecurity
@Configuration
package com.applesnt.config;
import org.springframework.context.annotation.Configuration;
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
@Configuration
public class CsrfSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();//关闭csrf 否则注册中心能启动,但是服务无法注册进来
super.configure(http); // 这一句必须要加上的,否则直接关闭密码验证服务了
}
}
5:访问Eureka(Eureka集群配置完成)
http://eureka1:8761/ http://eureka2:8762/ http://eureka3:8761/
二、构建Eureka Client
mhb-cloud-producer 【提供者 端口:9904】
mhb-cloud-consumer【消费者 端口:8802】
1:pom文件
mhb-cloud-producer mhb-cloud-consumer:加入Eureka Client依赖
<!--eureka客户端环境支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2:application.yml文件
mhb-cloud-producer:
应用名称:mhb-cloud-producer
端口:9904
Eureka注册方式:集群
debug: false #关闭debug模式
spring:
application:
name: mhb-cloud-producer #应用的名称
server:
port: 9904 #应用的端口号
eureka:
instance:
appname: producer #eureka application的名称
prefer-ip-address: true #开启ip显示eureka的主机服务
#eureka仪表盘的Instances格式
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
client:
service-url:
defaultZone: http://admin:123456@eureka1.com:8762/eureka/,http://admin:123456@eureka2.com:8762/eureka/,http://admin:123456@eureka3.com:8763/eureka/
#从eureka服务器注册表中获取注册表信息的时间间隔,默认30s
registry-fetch-interval-seconds: 30
#客户端发送变化同步到eureka服务器的时间间隔 默认30s
instance-info-replication-interval-seconds: 30
#询问eureka服务url信息的变化的间隔时间 默认300s
eureka-service-url-poll-interval-seconds: 300
#最初同步到eureka服务器的时间 默认40s
initial-instance-info-replication-interval-seconds: 40
#注册表是否压缩
g-zip-content: true
#eureka等待超时时间 默认是5s
eureka-server-connect-timeout-seconds: 5
#eureka等待读取时间 默认是8s
eureka-server-read-timeout-seconds: 8
#eureka客户端允许的所有eureka服务器连接的总数 默认200
eureka-server-total-connections: 200
mhb-cloud-consumer:
应用名称:mhb-cloud-consumer
端口:8802
Eureka注册方式:集群
debug: false
spring:
application:
name: mhb-cloud-consumer #每一个微服务必须有这个应用名称
server:
port: 8802 #端口
eureka:
instance:
appname: consumer #eureka application的名称
prefer-ip-address: true #开启ip显示eureka的主机服务
#eureka仪表盘的Instances格式
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
client:
service-url:
defaultZone: http://admin:123456@eureka1.com:8762/eureka/,http://admin:123456@eureka2.com:8762/eureka/,http://admin:123456@eureka3.com:8763/eureka/
#从eureka服务器注册表中获取注册表信息的时间间隔,默认30s
registry-fetch-interval-seconds: 30
#客户端发送变化同步到eureka服务器的时间间隔 默认30s
instance-info-replication-interval-seconds: 30
#询问eureka服务url信息的变化的间隔时间 默认300s
eureka-service-url-poll-interval-seconds: 300
#最初同步到eureka服务器的时间 默认40s
initial-instance-info-replication-interval-seconds: 40
#注册表是否压缩
g-zip-content: true
#eureka等待超时时间 默认是5s
eureka-server-connect-timeout-seconds: 5
#eureka等待读取时间 默认是8s
eureka-server-read-timeout-seconds: 8
#eureka客户端允许的所有eureka服务器连接的总数 默认200
eureka-server-total-connections: 200
3:在启动类开启eureka客户端注解
mhb-cloud-producer mhb-cloud-consumer:
@@EnableEurekaClient
package com.applesnt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient/*eureka客户端注解*/
public class MhbCloudProducerApplication {
public static void main(String[] args) {
SpringApplication.run(MhbCloudProducerApplication.class, args);
}
}
4:服务注册
分别启动 mhb-cloud-producer 和 mhb-cloud-consumer两个Eureka客户端项目
访问Eureka服务:http://eureka1:8761/
三、构建微服务通讯
1:在服务端创建测试controller【mhb-cloud-producer】
com\applesnt\controller\ProducerController.java
访问路径:http://localhost:9904/producer/get/123
/*类访问路径*/
@RequestMapping("/producer")
/*返回传递过来的id
* 请求路径:http://localhost:9904/producer/get/123
* */
@GetMapping("/get/{id}")
public String getId(@PathVariable("id") String id){
System.out.println("-----"+id);
return "我是提供者 端口是9904 传递的参数= "+id;
}
2:在消费端创建测试controller【mhb-cloud-consumer】
1:使用RestTemplate进行测试通讯,在启动类上获取RestTemplate对象:
@Bean
@LoadBalanced/*微服务通讯时需要负载均衡 相同的spring.applincatin.name*/
public RestTemplate balanceRestTemplate(){
return new RestTemplate();
}
2:创建消费端远程调用controller
com\applesnt\MhbCloudConsumerApplication.java
访问路径:http://localhost:8802/consumer/get/123
package com.applesnt.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @description: 消费者控制层
**/
@RestController
@RequestMapping("/consumer")
public class ConsumerController {
/*注入RestTemplate对象*/
@Autowired
@Qualifier("balanceRestTemplate")
private RestTemplate balanceRestTemplate;
@GetMapping("/get/{id}")
public String getId(@PathVariable String id){
//eureka方式 需要在启动类的RestTemplate加上@LoadBalanced负载均衡的注解
String returnId = balanceRestTemplate.getForObject("http://mhb-cloud-producer/producer/get/"+id,String.class);
System.out.println("returnId = "+returnId);
return returnId;
}
}
3:远程调用测试
消费者访问:http://localhost:8802/consumer/get/123
返回提供者的信息
四、Eureka服务端事件监听
EurekaInstanceCanceledEvent:服务下线事件
EurekaInstanceRegisteredEvent:服务注册事件
EurekaInstanceRenewedEvent:服务续约事件
EurekaRegistryAvailableEvent:eureka注册中心启动事件
EurekaServerStartedEvent: eureka server完全启动后事件
package com.applesnt.event;
import com.netflix.appinfo.InstanceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
/**
* @description: eureka事件监听
**/
@Component
@Slf4j
public class EurekaEventLinstener {
@EventListener/*实例注册事件*/
public void listen(EurekaInstanceRegisteredEvent event){
InstanceInfo instanceInfo = event.getInstanceInfo();
String name = instanceInfo.getAppName();
String id = instanceInfo.getInstanceId();
log.info(">>>>>>>"+id+":已经注册到eureka服务上 name="+name);
}
@EventListener/*实例续约事件*/
public void listen(EurekaInstanceRenewedEvent event){
InstanceInfo instanceInfo = event.getInstanceInfo();
String name = instanceInfo.getAppName();
String id = instanceInfo.getInstanceId();
log.info(">>>>>>>"+id+":续约时间触发 name="+name);
}
@EventListener/*eureka服务端注册并且是可用状态时事件*/
public void listen(EurekaRegistryAvailableEvent event){
log.info(">>>>>>>注册中心启动触发");
}
@EventListener/*eureka服务端完全启动成功后事件*/
public void listen(EurekaServerStartedEvent event){
log.info(">>>>>>>EurekaServer启动触发");
}
@EventListener/*实例下线事件*/
public void listen(EurekaInstanceCanceledEvent event){
String name = event.getAppName();
String id = event.getServerId();
log.info(">>>>>>>"+id+":下线成功 name="+name);
}
}
五、eureka自我保护
Eureka Server 在运行期间会去统计心跳失败比例在 15 分钟之内是否低于 85%,如果低于 85%,Eureka Server 会将这些实例保护起来,让这些实例不会过期!
解释:https://www.cnblogs.com/xishuai/p/spring-cloud-eureka-safe.html
关闭保护模式:生产环境不推荐关闭
eureka:
instance:
hostname: eureka1.com #eureka服务的主机 hosts文件映射了
server:
enable-self-preservation: false #关闭自我保护模式 生产环境不建议关闭