1.环境准备
1.JDK 17,Gradle 8.10.2,SpringBoot 3.0.2
2.Eureka-server
1.创建项目勾选所需的依赖
1.spring-boot-starter-security
2.spring-cloud-starter-netflix-eureka-server
3.spring-boot-starter-web
2.@EnableEurekaServer 注解启用服务注册
package com.gulimall.eurekaserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* @author yangfeifei
*/
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
3.禁用CSRF
package com.gulimall.eurekaserver.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
/**
* eureka-server
*
* @author yangfeifei
* @date 2025/2/18 16:36
* @description SecurityConfig
*/
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable() // 关闭CSRF保护(Eureka客户端不支持CSRF)
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/**").authenticated() // 匹配所有路径需要认证
)
.httpBasic();
return http.build();
}
}
4.服务端配置(application.yml)
# port
server:
port: 8000
# Spring Security
spring:
application:
name: eureka-server
security:
user:
name: your_username
password: your_password
eureka:
client:
register-with-eureka: true # false不将自己注册到Eureka服务器
fetch-registry: true # false不从Eureka服务器拉取注册表信息
serviceUrl:
defaultZone: http://${spring.security.user.name}:${spring.security.user.password}@localhost:${server.port}/eureka/ # 指定Eureka服务器地址
3.Eureka-client
1.创建项目勾选所需的依赖
1.spring-cloud-starter-netflix-eureka-client
2.spring-boot-starter-web
2.@EnableDiscoveryClient 注解启用客户端发现
package com.gulimall.eurekaclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author yangfeifei
*/
@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class, args);
}
}
3.客户端配置(application.yml)
# port
server:
port: 8001
spring:
application:
name: eureka-client
# Eureka
eureka:
client:
service-url:
defaultZone: http://your_username:your_password@localhost:8000/eureka/ # 指定Eureka服务器地址