eureka 注册中心;spring cloud的一个基础、非常重要的一个组件
作用:是用来记录每个微服务的ip、端口、项目名等关键信息,微服务之间能够更加方面互相访问
开发项目的时候需要开发注册中心模块,它也是一个微服务,需要单独运行
操作前需要提前配置好一个微服务:参考
创建一个微服务项目
①创建module模块作为注册中心微服务
②在pom文件中引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<!-- 引入eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
</dependencies>
③创建application.yml文件,添加配置
server:
port: 9001
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:9001/eureka/
④编写启动类,开启注册中心功能 启动项目测试
package com.woniuxy.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer //开启注册中心的功能
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
在浏览器地址栏输入:localhost:9001访问eureka管理页面
注册中心不许注册自己
将product、user模块都注册进注册中心
以product模块为例
①在product模块的pom文件中添加以下依赖,使自己能够成为eureka client
<!-- eureka -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
②在product的主启动类中开启eureka客户端功能
package com.woniuxy.product;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient //开启注册中心客户端功能
public class ProductApplication {
public static void main(String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
}
③修改product application.yml,添加eureka的配置
eureka:
client:
service-url:
defaultZone: http://elocalhost.com:9001/eureka/
instance:
instance-id: springcloud63-product-8002
prefer-ip-address: true
④先启动注册中心,然后再启动product模块
注册成功!
注意:
微服务名字:是微服务对应application.yml文件指定的名字,如图:
instance id就是在注册时指定的id
注意:注册user模块的方式与注册product模块的方式是一样的,只不过对于我们现在而言需要做以下几个操作:
•pom文件中引入eureka-client
•在主启动类开启注册客户端功能
•需要在application.yml文件中指定user模块的项目名(微服务名)
•需要进行注册的配置
运行user模块,user也被注册进来了
最后,给微服务添加解释说明,方面后期微服务的管理,因为微服务太多的话就不知道哪个微服务是干嘛的
①需要在对应的微服务里面添加依赖
<!-- 添加监控信息 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
②在对应的application.yml文件中配置信息
info:
app.name: this is my product module
developer.name: zr
date: 2020.3.25
language: Java
ip: 192.168.154.130
port: 8002
结果显示:
点击
显示: