1.我们在原先项目的基础上再新建一个项目cloud-demo-eureka
了解springcloud架构可以加求求:三五三六二四七二五九
此项目的依赖为
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-demo</artifactId>
<groupId>cn.org.zhixiang</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-demo-eureka</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<!--注意此处的依赖是SpringBoot2.0以后专用的,如果您使用的SpringBoot版本低于2.0请使用spring-cloud-starter-eureka-server-->
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.创建application.yml
spring:
application:
name: eureka-server
#开启权限认证
security:
basic:
enabled: true
user:
name: root
password: root
server:
host: localhost
port: 8761
eureka:
client:
#此项目不作为客户端注册
register-with-eureka: false
fetch-registry: false
service-url:
#开启权限验证后Eureka地址为 用户名:密码@地址:端口号,如未开启权限验证则直接使用 地址:端口号
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@${server.host}:${server.port}/eureka
3.创建cn.org.zhixiang包,在此包下创建CloudDemoEureApplication启动类
package cn.org.zhixiang;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class CloudDemoEureApplication {
public static void main(String[] args) {
SpringApplication.run(CloudDemoEureApplication.class, args);
}
}
4.如果您开启了权限验证并且SpringBoot版本为2.0以上的话还需要一个操作,如果不是此布可以忽略
因为2.0默认开启了csrf,如果我们现在直接启动Eureka服务的话客户端是注册不上的,所以需要把csrf关闭
在cn.org.zhixiang包下新建security包,新建WebSecurityConfigurer类
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
super.configure(http);
}
}
5.在CloudDemoEureApplication启动类中启动Eureka服务,浏览器访问http://localhost:8761/eureka,输入用户名root和密码root登陆Eureka后Eureka服务创建成功。