Eureka能够自动注册并发现微服务,然后对服务的状态、信息进行集中管理,这样当我们需要获取其他服务的信息时,我们只需要向Eureka进行查询就可以了
1.注册Eureka
1)创建maven项目在父依赖中导入
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2021.0.1</version> <type>pom</type> <scope>import</scope> </dependency>
2)Eureka子项目导入
servlet-api会与wweb启动依赖冲突所以要去掉
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> <version>3.1.2</version> <exclusions> <exclusion> <artifactId>servlet-api</artifactId> <groupId>javax.servlet</groupId> </exclusion> </exclusions> <type>pom</type> </dependency>
3.配置yml文件
server: port: 8888 eureka: # 开启之前需要修改一下客户端设置(虽然是服务端 client: # 由于我们是作为服务端角色,所以不需要获取服务端,改为false,默认为true fetch-registry: false # 暂时不需要将自己也注册到Eureka register-with-eureka: false # 将eureka服务端指向自己 service-url: defaultZone: http://localhost:8888/eureka spring: datasource: username: root password: 1234 url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver
4)在启动类增加注解
@SpringBootApplication @EnableEurekaServer//开启服务 public class EuApplication { public static void main(String[] args) { SpringApplication.run(EuApplication.class,args); } }
6)在自己的子服务中导入eureka的client依赖同样要去掉servlet-api
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>3.1.3</version> <exclusions> <exclusion> <artifactId>servlet-api</artifactId> <groupId>javax.servlet</groupId> </exclusion> </exclusions> </dependency>
7)在自己的子服务的yml中配置eureka
server: port: 8002 spring: datasource: username: root password: 1234 url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver application: name: userservice mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.peng.pojo eureka: client: # 跟上面一样,需要指向Eureka服务端地址,这样才能进行注册 service-url: defaultZone: http://localhost:8888/eureka
8)先启动Eureka在启动服务,就能看到服务应被注册进去了