Spring Boot 十大开源 “王炸”
2025-07-17 09:35·金属时代ok
2.1 ShedLock
ShedLock 可确保计划任务在同一时间最多执行一次。如果一个任务正在一个节点上执行,它就会获得一个锁,阻止另一个节点(或线程)执行同一任务。
请注意,如果一个任务已在一个节点上执行,其他节点上的任务执行不会等待,而是直接跳过。
ShedLock 使用 Mongo、JDBC 数据库、Redis、Hazelcast、ZooKeeper 或其他外部存储进行协调。
依赖坐标
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>6.9.2</version>
</dependency>
<!--本案例基于redis实现,所以要引入如下依赖-->
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-redis-spring</artifactId>
<version>6.9.2</version>
</dependency>
基本使用
// 开启功能
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "10m")
public class AppConfig {
@Bean
LockProvider redisLockProvider(RedisConnectionFactory factory) {
return new RedisLockProvider(factory) ;
}
}
// 定时任务
@Scheduled(...)
@SchedulerLock(name = "scheduledTaskName")
public void scheduledTask() {
// TODO
}
详细使用请查看下面官方链接:
https://github.com/lukas-krecan/ShedLock
2.2 p6spy
P6Spy 是一个可无缝拦截和记录数据库数据的框架,无需更改现有应用程序的代码。P6Spy 发行版包括 P6Log,这是一个可记录任何 Java 应用程序的所有 JDBC 事务的应用程序。
依赖坐标
<dependency>
<groupId>com.github.gavlyukovskiy</groupId>
<artifactId>p6spy-spring-boot-starter</artifactId>
<version>1.11.0</version>
</dependency>
配置文件
decorator:
datasource:
p6spy:
enable-logging: true
logging: slf4j
当执行相关SQL操作时,日志输出如下:
详细使用请查看下面官方链接:
https://github.com/gavlyukovskiy/spring-boot-data-source-decorator
2.3 Logbook
Logbook 是一款可扩展的 Java 库,能够为不同的客户端和服务器端技术实现完整的请求与响应日志记录功能。它满足了一项特殊需求:
允许 Web 应用开发者记录应用程序接收或发送的所有 HTTP 流量
以一种便于后续持久化存储和分析的方式进行记录。这在传统日志分析、满足审计要求或调查单个历史流量问题等场景中非常实用。
依赖坐标
<dependency>
<groupId>org.zalando</groupId>
<artifactId>logbook-spring-boot-starter</artifactId>
<version>3.12.2</version>
</dependency>
配置文件
logging:
level:
'[org.zalando.logbook.Logbook]': TRACE
如上配置后,接下来随意访问一个Controller接口后,日志输出如下:
我们也可以进行如下的自定义配置:
@Bean
public Logbook logbook() {
Logbook logbook = Logbook.builder()
.condition(Conditions.exclude(Conditions.requestTo("/api/query"),
Conditions.contentType("application/octet-stream"),
Conditions.header("X-Secret", "true")))
.sink(new DefaultSink(new DefaultHttpLogFormatter(), new DefaultHttpLogWriter()))
.build();
return logbook;
}
详细使用请查看下面官方链接:
https://github.com/zalando/logbook
2.4 Jasypt
Jasypt Spring Boot 为 Spring Boot 应用程序的属性源(property sources)提供加密支持。
依赖坐标
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
基本使用
// 使用jasypt工具加密数据
java org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI
input="xxxooo"
password="aaaabbbbcccc6666"
algorithm="PBEWithMD5AndDES"
直接运行上面的命令后,输出:
使用上面的密文
spring:
datasource:
password: ENC(x8hoXK78YcyblFzV3vohDA==)
启动应用后,需要指定如下配置
java -jar app.jar –jasypt.encryptor.password=aaaabbbbbcccc6666
详细使用请查看下面的官方链接:
https://github.com/ulisesbocchio/jasypt-spring-boot
2.5 Bucket4j
Bucket4j 是一个基于令牌桶算法(token-bucket algorithm)的 Java 限流库。它是一个线程安全的库,既可用于独立的 JVM 应用程序,也可用于集群环境。此外,它还支持通过 JCache(JSR107)规范实现内存缓存或分布式缓存。
依赖坐标
<dependency>
<groupId>com.giffing.bucket4j.spring.boot.starter</groupId>
<artifactId>bucket4j-spring-boot-starter</artifactId>
<version>0.12.10</version>
</dependency>
<dependency>
<groupId>com.bucket4j</groupId>
<artifactId>bucket4j-redis</artifactId>
<version>8.10.1</version>
</dependency>
配置文件
bucket4j:
cache-to-use: redis-lettuce
filters:
- filter-method: webflux
cache-name: product-cache
id: product_filter
url: /products/.*
rate-limits:
-
#这里的cache-key非常关键;用于区分不同请求的情况;
#比如,这里我会根据不同的请求id来现在访问速率
#这里可以写spel表达式,这里调用的是HttpServletRequest#getParameter方法
cache-key: getParameter("id")
bandwidths:
#配置桶的容量
- capacity: 2
# 时间
time: 30
# 单位
unit: seconds
# 填充速度;这会每隔30秒进行填充
refill-speed: interval
配置类
@Bean
RedisClient redisClient() {
RedisURI redisURI = RedisURI.create("localhost", 6379) ;
redisURI.setDatabase(6) ;
redisURI.setCredentialsProvider(new RedisCredentialsProvider() {
@Override
public Mono<RedisCredentials> resolveCredentials() {
return Mono.just(RedisCredentials.just(null, "123123"));
}
});
return RedisClient.create(redisURI) ;
}
访问/products/xxx接口,结果如下:
2.6 gRPC
gRPC-Spring-Boot-Starter 将 Google的开源高性能RPC框架 与 Spring Boot 进行整合 该项目简化了 gRPC 服务端 / 客户端的设置,只需要为项目添加了一个依赖项,并在服务实现类 / 客户 (stub) 字段上添加了一个的注解。 这个项目提供的特性仍然能复用您使用 gRPC 的经验,并且允许你执行任何自定义操作。
依赖坐标
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-spring-boot-starter</artifactId>
<version>3.1.0.RELEASE</version>
</dependency>
配置文件
grpc:
client:
GLOBAL:
address: localhost:7777
negotiation-type: plaintext
# 服务端配置
grpc:
server:
port: 7777
# 客户端配置
grpc:
client:
GLOBAL:
address: localhost:7777
xxxooo:
address: localhost:7777
negotiation-type: plaintext
官方详细文档:
https://grpc-ecosystem.github.io/grpc-spring/zh-CN/
2.7 Retrofit
Retrofit 是一个类型安全的 HTTP 客户端库,专为 Java 和 Android 开发设计,用于简化网络请求与服务器交互的流程。
retrofit-spring-boot-starter,支持快速集成和功能增强。
Spring Boot 3.x 项目,请使用retrofit-spring-boot-starter 3.x
Spring Boot 1.x/2.x 项目,请使用retrofit-spring-boot-starter 2.x。
依赖坐标
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>3.1.7</version>
</dependency>
定义接口
@RetrofitClient(baseUrl = "${test.baseUrl}")
public interface UserService {
/**根据id查询用户姓名*/
@POST("getName")
String getName(@Query("id") Long id);
}
注入使用
@Service
public class BusinessService {
private final UserService userService;
public BusinessService(UserService userService) {
this.userService = userService ;
}
public void doBusiness() {
// call userService
}
}
详细使用请查看官方链接
https://github.com/LianjiaTech/retrofit-spring-boot-starter
2.8 MapStruct-Plus
MapStruct Plus 是对 MapStruct 框架的增强工具。它仅提供扩展功能,不会对原有框架进行修改,并能通过注解自动生成两个类之间的转换逻辑,省去了手动定义 MapStruct 接口的操作,让 Java 类型转换更加简洁优雅。
依赖坐标
<dependency>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus-spring-boot-starter</artifactId>
<version>1.4.8</version>
<scope>runtime</scope>
</dependency>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>21</source>
<target>21</target>
<annotationProcessorPaths>
<path>
<groupId>io.github.linpeilie</groupId>
<artifactId>mapstruct-plus-processor</artifactId>
<version>1.4.8</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
基本使用
@AutoMapper(target = UserDto.class)
public class User {
private String name ;
private Integer age ;
}
public class UserDto {
private String name ;
private Integer age ;
}
如上配置&定义完后,会自动生成如下的类:
测试如下
@Resource
private Converter converter;
@Test
public void test() {
User user = new User();
user.setName("jack");
user.setAge(23) ;
UserDto userDto = converter.convert(user, UserDto.class);
System.out.println(userDto);
}
详细使用请查看下面官方文档:
https://github.com/linpeilie/mapstruct-plus
2.9 Redisson
Redisson 是面向 Valkey 和 Redis 的 Java 客户端及实时数据平台,为使用 Valkey 或 Redis 提供了最为便捷、简易的操作方式。Redisson 对象在 Valkey 或 Redis 与 Java 代码之间构建了抽象层,使开发者能够专注于数据建模和应用逻辑。
依赖坐标
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.50.0</version>
</dependency>
注意:该starter依赖与最新版 Spring Boot 兼容的 redisson-spring-data 模块
如下分布式锁示例
RLock lock = redisson.getLock("myLock");
// 传统加锁方式
lock.lock();
// 或获取锁,并在 10 秒后自动解锁
lock.lock(10, TimeUnit.SECONDS);
// 或等待锁获取,最长等待 100 秒,获取后 10 秒自动解锁
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
if (res) {
try {
// ...
} finally {
lock.unlock();
}
}
更多更加详细的使用请查看下面官方链接:
https://github.com/redisson/redisson?tab=readme-ov-file
2.10 Resilience4j
Resilience4j 是一款专为函数式编程设计的轻量级容错库。Resilience4j 提供高阶函数(装饰器),可用于为任何函数式接口、Lambda 表达式或方法引用添加断路器(Circuit Breaker)、限流器(Rate Limiter)、重试机制(Retry)或舱壁模式(Bulkhead)等功能。你可以在任何函数式接口、Lambda 表达式或方法引用上叠加使用多个装饰器。其优势在于,你可以根据需求自由选择所需的装饰器,而无需引入其他不必要的功能。
依赖坐标
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>2.3.0</version>
</dependency>
基本使用
resilience4j:
circuitbreaker:
configs:
userCfg:
minimum-number-of-calls: 2
wait-duration-in-open-state: 10s
findById:
minimum-number-of-calls: 3
wait-duration-in-open-state: 10s
instances:
userList:
base-config: userCfg
业务代码
private final CircuitBreakerRegistry circuitBreakerRegistry ;
public UserService(CircuitBreakerRegistry circuitBreakerRegistry) {
this.circuitBreakerRegistry = circuitBreakerRegistry ;
}
@CircuitBreaker(name = "userList", fallbackMethod = "findAllFallback")
public List<User> findAll() {
System.out.println(1 / 0) ;
try {
TimeUnit.MILLISECONDS.sleep(2000) ;
} catch (InterruptedException e) {}
return List.of(
new User(1L, "Pack", 20),
new User(2L, "Jack", 22),
new User(3L, "Wake", 24),
new User(4L, "Caoo", 26)
) ;
}
// 降级方法
public List<User> findAllFallback(Throwable ex) {
System.err.printf("发生异常: %s%n", ex.getMessage()) ;
return List.of() ;
}
当上面的业务方法发生异常后会自动的调用 findAllFallback 降级方法。
详细使用请查看下面官方链接:
https://resilience4j.readme.io/docs/getting-started