@TOC
springcloud项目
1. 搭建Eureka注册中心
1) 通过向导创建 Eureka Server,Spring Cloud Discovery → Eureka Server
2) pom.xml
把spring-boot-starter-parent的version改成2.1.4.RELEASE
把spring-cloud.version改成Greenwich.SR1
3) application.yml
server:
port: 7776
eureka:
client:
service-url:
defaultZone: http://localhost:7776/eureka/
register-with-eureka: false
fetch-registry: false
4) 启动类注解@EnableEurekaServer
5) 启动, 访问http://localhost:7776
6) 自我保护机制,高可用,上线后不要关闭,开发时可以关
eureka:
server:
enable-self-preservation: false
2. 搭建Eureka Client
1) Spring Cloud Discovery → Eureka Discovery Client
2) pom.xml
把spring-boot-starter-parent的version改成2.1.4.RELEASE
把spring-cloud.version改成Greenwich.SR1
3) application.yml
server:
port: 8081
spring:
application:
name: demo-eureka-provider
eureka:
client:
service-url:
defaultZone: http://localhost:7776/eureka/
在7776端口注册
4) Provider 启动类注解@EnableDiscoveryClient
5) 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
运行启动类,访问
给yml文件添加集群,这里除了端口和内部的识别名称不一样,其它的应用名和注册中心一样
server:
port: 8081
spring:
profiles: c1
---
server:
port: 8082
spring:
profiles: c2
---
spring:
application:
name: eureka-client
eureka:
client:
service-url:
defaultZone: http://root:123456@server1:7776/eureka/,http://root:123456@server2:7777/eureka/
--spring.profiles.active=c1
分别启动1和2,会出现两个同名应用
释义
定义应用名称
相同的应用名,不同的端口,注册进来的东西自动形成一个集群
springcloud如何判断集群-应用名相同,IP或者端口不同,是一个集群
3. 注册中心添加用户认证(server)
1) 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2) 添加配置
spring:
security:
user:
name: root
password: 123456
server:
port: 7776
eureka:
client:
service-url:
defaultZone: http://root:123456@localhost:7776/eureka/
register-with-eureka: false
fetch-registry: false
spring:
security:
basic:
enabled: true
user:
name: root
password: 123456
3) 添加配置文件类
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable(); //关闭csrf
super.configure(http); //开启认证
}
}
4) 修改服务器和客户端的注册中心地址
http://用户名:密码@localhost:7776/eureka/
需要客户端和服务端都有账号密码才行,不然就注册不进来,因为注册中心不是实时刷新,可能有时候还会存在
4. 多注册中心
表示可以被其它注册中心发现,可以注册别的注册中心
1) 注册中心修改
spring:
application:
name: demo-eureka-server
eureka:
instance:
hostname: server1 # hosts文件中配置域名解析,hostname要不同
client:
service-url:
defaultZone: http://root:123456@server2:7777/eureka/ #其他注册中心
register-with-eureka: true
fetch-registry: true
将server集群化
可以访问两个
2) 注意: 单机模拟时, 需要在C:\Windows\System32\drivers\etc\hosts文件中配置主机名
例: 127.0.0.1 server1
127.0.0.1 server2
2) 创建其它的注册中心应用
可以使用IDEA将单个web应用集群化的方式进行处理