SpringCloud Eureka安装和使用,SpringCloud使用Eureka作为服务注册中心
================================
©Copyright 蕃薯耀 2021-03-08
https://www.cnblogs.com/fanshuyao/
一、Eureka功能点server:Eureka Server(服务注册中心)provider:Eureka Client(服务提供者)+Actuator(服务器监控)consumer:Eureka Client(服务器消费者)+Actuator(服务器监控)+Ribbon(负载均衡)
二、Eureka server服务端
1、引入Pom依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.4</version>
</dependency>
2、application.properties文件配置
server.port=8501
spring.application.name=springCloud-eureka-server
#eureka服务端的实例名称,eureka8501.com需要修改host文件
eureka.instance.hostname=eureka8501.com
#客户端服务名
#eureka.instance.appname=${spring.application.name}
# 是否向注册中心注册自己,缺省:true
# 一般情况下,Eureka服务端是不需要再注册自己的,false表示不向注册中心注册自己
eureka.client.register-with-eureka=false
# 是否从Eureka获取注册信息,缺省:true
# 一般情况下,Eureka服务端是不需要的
eureka.client.fetch-registry=false
# Eureka服务器的地址,类型为HashMap,缺省的Key为 defaultZone;缺省的Value为 http://localhost:8761/eureka
#如果是单机,配置自己的地址:http://eureka8501.com:8501/eureka,同样可以配置成:http://${eureka.instance.hostname}:${server.port}/eureka
#如果是集群(服务端),在这里需要配置其他eureka server的地址,用逗号进行分隔,如http://192.168.170.11:7000/eureka,http://192.168.170.12:9000/eureka
#格式为:http://${eureka.instance.hostname}:${server.port}/eureka
eureka.client.service-url.defaultZone=http://eureka8501.com:8501/eureka
#关闭自我保护机制,保证不可用服务被及时移除
eureka.server.enable-self-preservation=false
#3秒后移除
eureka.server.eviction-interval-timer-in-ms=3000
3、启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class SpringCloudEurekaServer8501Application {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaServer8501Application.class, args);
}
}
三、Eureka provider - 服务提供者端
1、引入Pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.4</version>
</dependency>
2、application.properties文件配置
server.port=8601
spring.application.name=springCloud-eureka-server
#eureka实例名称
#eureka.instance.hostname=eureka8601.com
eureka.instance.instance-id=eureka8601
#路径显示IP地址
eureka.instance.prefer-ip-address=true
#eureka客户端向服务端发送心跳的时间间隔,单元为秒,默认为30秒
eureka.instance.lease-renewal-interval-in-seconds=2
#eureka服务端收到最后一次心跳等待的时间上限,超时将移除服务,单元为秒,默认为90秒
eureka.instance.lease-expiration-duration-in-seconds=5
#false表示向注册中心注册自己
eureka.client.register-with-eureka=true
#是否从Eureka抓取已有的注册信息,默认为true。单节点不用设置,集群必须设置为true,才能配置ribbon使用负载均衡
eureka.client.fetch-registry=true
#设置与Eureka server交互的地址查询服务和注册服务都需要依赖这个地址
eureka.client.service-url.defaultZone=http://eureka8501.com:8501/eureka
#集群配置
#eureka.client.service-url.defaultZone=http://eureka8501.com:8501/eureka,http://eureka8502.com:8501/eureka
3、启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class SpringCloudEurekaClient8601Application {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaClient8601Application.class, args);
}
}
4、服务类
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ClientController {
@Value("${server.port}")
private String serverPort;
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping("/test")
public Result test() {
return Result.ok("端口:" + serverPort);
}
@RequestMapping("/discoveryClient")
public Result discoveryClient() {
List<String> services = discoveryClient.getServices();
for (String service : services) {
System.out.println("===service = " + service);
System.out.println("");
List<ServiceInstance> serviceInstances = discoveryClient.getInstances(service);
for (ServiceInstance serviceInstance : serviceInstances) {
System.out.println("+++getInstanceId = " + serviceInstance.getInstanceId());
System.out.println("+++getHost = " + serviceInstance.getHost());
System.out.println("+++getPort = " + serviceInstance.getPort());
System.out.println("+++getUri = " + serviceInstance.getUri());
System.out.println("");
}
System.out.println("-------------------------------------");
}
return Result.ok(discoveryClient);
}
}
import java.util.Date;
import cn.hutool.core.date.DateUtil;
public class Result {
public static final String SUCCESS = "操作成功。";
public static final String FAILURE = "操作失败!";
private boolean result;
private String timestamp;
private String msg;
private Object datas;
private Result() {}
public static Result ok() {
return Result.ok(SUCCESS, null);
}
public static Result ok(Object datas) {
return Result.ok(SUCCESS, datas);
}
public static Result okMsg(String msg) {
return Result.ok(msg, null);
}
public static Result ok(String msg, Object datas) {
Result result = new Result();
result.setResult(true);
result.setTimestamp(DateUtil.formatDateTime(new Date()));
if(msg == null || msg == "" || msg.trim() == "") {
result.setMsg(SUCCESS);
}else {
result.setMsg(msg);
}
result.setDatas(datas);
return result;
}
public static Result fail() {
return Result.fail(FAILURE, null);
}
public static Result failMsg(String msg) {
return Result.fail(msg, null);
}
public static Result fail(Object datas) {
return Result.fail(FAILURE, datas);
}
public static Result fail(String msg, Object datas) {
Result result = new Result();
result.setResult(false);
result.setTimestamp(DateUtil.formatDateTime(new Date()));
if(msg == null || msg == "" || msg.trim() == "") {
result.setMsg(FAILURE);
}else {
result.setMsg(msg);
}
result.setDatas(datas);
return result;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getDatas() {
return datas;
}
public void setDatas(Object datas) {
this.datas = datas;
}
public static void main(String[] args) {
}
}
四、Eureka consumer - 服务消费者端
1、引入Pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.4</version>
</dependency>
2、application.properties文件配置
server.port=8701
spring.application.name=springCloud-eureka-web
#eureka服务端的实例名称
eureka.instance.hostname=eureka8701.com
#eureka实例名称
eureka.instance.instance-id=eureka8701
#路径显示IP地址
eureka.instance.prefer-ip-address=true
#eureka客户端向服务端发送心跳的时间间隔,单元为秒,默认为30秒
eureka.instance.lease-renewal-interval-in-seconds=2
#eureka服务端收到最后一次心跳等待的时间上限,超时将移除服务,单元为秒,默认为90秒
eureka.instance.lease-expiration-duration-in-seconds=5
#false表示向注册中心注册自己
eureka.client.register-with-eureka=false
#是否从Eureka抓取已有的注册信息,默认为true。单节点不用设置,集群必须设置为true,才能配置ribbon使用负载均衡
eureka.client.fetch-registry=true
#设置与Eureka server交互的地址查询服务和注册服务都需要依赖这个地址
eureka.client.service-url.defaultZone=http://eureka8501.com:8501/eureka
3、启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class SpringCloudEurekaWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudEurekaWebApplication.class, args);
}
}
4、RestTemplate类
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestConfig {
//@LoadBalanced实现负载均衡
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
5、服务请求类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping("/web")
public class TestController {
//private String serviceUrl = "http://eureka8601.com:8601";
//springCloud使用RestTemplate,如果使用了服务的地址,RestTemplate必须加上@LoadBalanced注解,不然会java.net.UnknownHostException
private String serviceUrl = "http://SPRINGCLOUD-EUREKA-SERVER";
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value="/get", produces = MediaType.APPLICATION_JSON_VALUE)
public Result get() {
Result result = restTemplate.getForObject(serviceUrl + "/test", Result.class);
return result;
}
}
五、eureka配置项解析
1、eureka通用配置
# 应用名称,将会显示在Eureka界面的应用名称
spring.application.name=config-service
# 应用端口,Eureka服务端默认为:8761
server.port=3333
2、eureka.server前缀的配置项
# 是否允许开启自我保护模式,缺省:true
# 当Eureka服务器在短时间内丢失过多客户端时,自我保护模式可使服务端不再删除失去连接的客户端
eureka.server.enable-self-preservation = false
# Peer节点更新间隔,单位:毫秒
eureka.server.peer-eureka-nodes-update-interval-ms =
# Eureka服务器清理无效节点的时间间隔,单位:毫秒,缺省:60000,即60秒
eureka.server.eviction-interval-timer-in-ms = 60000
3、eureka.instance前缀的配置项
# 服务名,默认取 spring.application.name 配置值,如果没有则为 unknown
eureka.instance.appname = eureka-client
# 实例ID
eureka.instance.instance-id = eureka-client-instance1
# 应用实例主机名
eureka.instance.hostname = localhost
# 客户端在注册时使用自己的IP而不是主机名,缺省:false
eureka.instance.prefer-ip-address = false
# 应用实例IP
eureka.instance.ip-address = 127.0.0.1
# 服务失效时间,失效的服务将被剔除。单位:秒,默认:90
eureka.instance.lease-expiration-duration-in-seconds = 90
# 服务续约(心跳)频率,单位:秒,缺省30
eureka.instance.lease-renewal-interval-in-seconds = 30
# 状态页面的URL,相对路径,默认使用 HTTP 访问,如需使用 HTTPS则要使用绝对路径配置,缺省:/info
eureka.instance.status-page-url-path = /info
# 健康检查页面的URL,相对路径,默认使用 HTTP 访问,如需使用 HTTPS则要使用绝对路径配置,缺省:/health
eureka.instance.health-check-url-path = /health
4、eureka.client前缀的配置项
# Eureka服务器的地址,类型为HashMap,缺省的Key为 defaultZone;缺省的Value为 http://localhost:8761/eureka
# 如果服务注册中心为高可用集群时,多个注册中心地址以逗号分隔。
eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka
# 是否向注册中心注册自己,缺省:true
# 一般情况下,Eureka服务端是不需要再注册自己的
eureka.client.register-with-eureka = true
# 是否从Eureka获取注册信息,缺省:true
# 一般情况下,Eureka服务端是不需要的
eureka.client.fetch-registry = true
# 客户端拉取服务注册信息间隔,单位:秒,缺省:30
eureka.client.registry-fetch-interval-seconds = 30
# 是否启用客户端健康检查
eureka.client.health-check.enabled = true
#
eureka.client.eureka-service-url-poll-interval-seconds = 60
# 连接Eureka服务器的超时时间,单位:秒,缺省:5
eureka.client.eureka-server-connect-timeout-seconds = 5
# 从Eureka服务器读取信息的超时时间,单位:秒,缺省:8
eureka.client.eureka-server-read-timeout-seconds = 8
# 获取实例时是否只保留状态为 UP 的实例,缺省:true
eureka.client.filter-only-up-instances = true
# Eureka服务端连接空闲时的关闭时间,单位:秒,缺省:30
eureka.client.eureka-connection-idle-timeout-seconds = 30
# 从Eureka客户端到所有Eureka服务端的连接总数,缺省:200
eureka.client.eureka-server-total-connections = 200
# 从Eureka客户端到每个Eureka服务主机的连接总数,缺省:50
eureka.client.eureka-server-total-connections-per-host = 50
![](https://i-blog.csdnimg.cn/blog_migrate/88ee0e7f25acfd97f983225983987fac.png)
(时间宝贵,分享不易,捐赠回馈,^_^)
================================
©Copyright 蕃薯耀 2021-03-08
https://www.cnblogs.com/fanshuyao/