参考(14条消息) Spring Cloud Eureka详解_sunhuiliang85的专栏-CSDN博客
spring cloud eureka服务端
生产环境中可以加上spring security防止别人看到这个页面,不安全
添加起步依赖
<!--spring cloud eureka服务端起步依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
在springboot启动类中添加注解
@SpringBootApplication
//启用eureka server
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class,args);
}
}
配置
server:
port: 9999
eureka:
instance:
hostname: localhost
ip-address: 127.0.0.1
prefer-ip-address: true #启用ip地址注册
#续约到期,服务时效时间,默认90秒
#Eureka服务端在收到最后一次心跳后等待时间的一个上限,单位为秒(默认是90秒),超市将剔除服务
lease-expiration-duration-in-seconds: 60
#续约间隔时间 心跳检测时间
#Eureka客户端向服务端发送心跳时间的间隔,单位为秒(默认是30秒)
lease-renewal-interval-in-seconds: 30
client:
register-with-eureka: false #是否将自己注册到eureka服务器中,默认是ture eureka集群配置true
fetch-registry: false #是否从eureka中拉取服务信息 不需要,集群需要拉取
#客户端连接地址
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
server:
#设置剔除无效服务的间隔毫秒值,对无效服务链接进行删除
eviction-interval-timer-in-ms: 5000
#关闭自我保护机制,保证不可用服务及时剔除
enable-self-preservation: false
spring:
application:
name: eureka-server1
客户端依赖
<!--eureka客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
配置
server:
port: 18081
#配置数据源
spring:
datasource:
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
application:
name: user-provider1
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9999/eureka/
#表示多久去注册中心拉取一次服务信息
registry-fetch-interval-seconds: 30
#Eureka客户端向服务端发送心跳时间的间隔,单位为秒(默认是30秒)
instance:
#向注册中心发起心跳
lease-renewal-interval-in-seconds: 1
启动类
@SpringBootApplication
@EnableJpaRepositories//开启jpa自动配置
@EnableEurekaClient
public class UserProviderApplication {
public static void main(String[] args) {
SpringApplication.run(UserProviderApplication.class,args);
}
}
使用
@Autowired
private EurekaClient discoveryClient;
//用下面这个
//@Autowired
//private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@GetMapping("look")
public User look(){
InstanceInfo nextServerFromEureka = discoveryClient.getNextServerFromEureka("user-provider", true);
String homePageUrl = nextServerFromEureka.getHomePageUrl();
//System.out.println(homePageUrl);//http://localhost:18081/
User user = restTemplate.getForObject(homePageUrl + "user/2", User.class);
return user;
}