本文共 4166 字,大约阅读时间需要 13 分钟。
要搭建一个Eureka注册中心,首先需要配置服务器端的pom文件和启动类。
在项目的pom文件中添加以下依赖:
org.springframework.cloud spring-cloud-starter-eureka-server
完整的pom文件示例如下:
4.0.0 com.atguigu.springcloud microservicecloud 0.0.1-SNAPSHOT microservicecloud-eureka-7001 org.springframework.cloud spring-cloud-starter-eureka-server org.springframework springloaded
Eureka服务器端的服务端配置文件(eureka.yml
)内容如下:
server: port: 7001eureka: instance: hostname: localhost client: register-with-eureka: false fetch-registry: false service-url: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
启动服务器端的类使用Spring Boot注解:
@SpringBootApplication@EnableEurekaServerpublic class EurekaServer7001_App { public static void main(String[] args) { SpringApplication.run(EurekaServer7001_App.class, args); }}
Provider服务需要注册到Eureka服务中。同样在项目的pom文件中添加以下依赖:
org.springframework.cloud spring-cloud-starter-eureka
完整的pom文件示例如下:
4.0.0 com.atguigu.springcloud microservicecloud 0.0.1-SNAPSHOT microservicecloud-provider-dept-8001 com.atguigu.springcloud microservicecloud-api ${project.version} org.springframework.cloud spring-cloud-starter-eureka
服务提供者的配置文件(application.yml
)内容如下:
server: port: 8001mybatis: config-location: classpath:mybatis/mybatis.cfg.xml type-aliases-package: com.atguigu.springcloud.entities mapper-locations: classpath:mybatis/mapper/**/*.xmlspring: application: name: microservicecloud-dept datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: org.gjt.mm.mysql.Driver url: jdbc:mysql://localhost:3306/cloudDB01 username: root password: 123456 dbcp2: min-idle: 5 initial-size: 5 max-total: 5 max-wait-millis: 200eureka: client: service-url: defaultZone: http://localhost:7001/eureka/ instance: instance-id: microservicecloud-dept8001 prefer-ip-address: true info: app.name: atguigu-microservicecloud company.name: www.atguigu.com build.artifactId: ${project.artifactId} build.version: ${project.version}
启动服务的Provider类:
@SpringBootApplication@EnableEurekaClientpublic class DeptProvider8001_App { public static void main(String[] args) { SpringApplication.run(DeptProvider8001_App.class, args); }}
为了实现Eureka的集群,我们需要配置多个注册中心并确保各服务能够正确 discoveries。
在Eureka服务器端的配置文件中添加服务的 listen地址:
server: port: 7001eureka: instance: hostname: eureka7001.com client: service-url: defaultZone: http://${eureka.instance.hostname}:7001/eureka/
对于其他注册中心(如eureka7002.com和eureka7003.com),配置方式类似。
在客户端的配置文件中指定多个 registering address:
server: port: 80spring: application: name: microservicecloud-dept eureka: client: service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
可以通过访问http://eureka7001.com:7001/
或其他节点地址查看注册信息,确保服务注册和发现正常。
通过以上配置,可以实现Eureka服务的注册中心搭建及集群部署,方便各服务之间的功能调用和负载均衡。
转载地址:http://skojz.baihongyu.com/