Spring_cloud-Eureka
一. 注册中心概述
本文仅供单个模块代码的提示,如想知整套demo,请留言!
cap原理图解:
Eureka注册中心的客户端消费者会缓存地址信息到本地,这就造成了信息不一致,也就是cap原理的ap;
二.使用Eureka的步骤
Eureka是服务注册中心,只做服务注册;自身并不提供服务也不消费服务。可以搭建web工程使用Eureka,可以使用Spring Boot方式搭建。
1.搭建Eureka
步骤:
-
创建一个maven工程;
-
导入坐标
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
- 配置application.yml文件
spring:
application:
name: eureka-server
server:
port: 9000 #端口
#配置eureka server
eureka:
instance:
hostname: localhost #主机地址名称
client:
register-with-eureka: false # 是否将自己注册到注册中心
fetch-registry: false # 是否从eureka中获取注册信息
service-url: #配置暴露给Eureka Client(客户端)的请求地址
defaultZone: http://127.0.0.1:9000/eureka/ # eureka 服务地址,如果是集群的话;需要指定其它集群eureka地址,使用逗号隔开
#或者 http://${
eureka.client.instance.hostname}:${
server.port}/eureka/
- 配置启动类:一个注解@EnableEurekaServer
package cn.itcast.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableEurekaServer //激活EurekaServer
class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class,args);
}
}
2.将服务提供者注册到EurekaServer上
1. 引入EurekaClient的坐标
<!--引入eureka-client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2. 修改application.yml 添加EurekaServer的相关信息
server:
port: 9001 #端口
spring:
application:
name: service-product #服务名称
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf8
username: root
password: root
jpa:
database: MySQL
show-sql: true
open-in-view: true
#配置Eureka
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:9000/eureka/ #EurekaService的路径
instance:
prefer-ip-address: true #使用ip地址注册
3.修改启动类,添加服务发现的支持(可选)
//激活Eureka(两个注解都可以),新版本可以不写
@EnableEurekaClient
@EnableDiscoveryClient
3.服务消费者通过注册中心获取服务列表,并调用
1.引入坐标
<!--引入eureka-client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<art