SpringBoot中集成Redis進行緩存的實現(xiàn)
在Spring Boot中集成Redis進行緩存,主要分為以下步驟:
1. 添加依賴
在pom.xml
中添加Redis和緩存相關(guān)的依賴:
<!-- Spring Boot Redis Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!-- 可選:對象序列化支持(如Jackson) --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency>
2. 配置Redis連接
在application.properties
或application.yml
中配置Redis服務(wù)器信息:
# Redis基礎(chǔ)配置 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= # 若無密碼則留空 spring.redis.database=0 # 連接池配置(可選) spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0
3. 啟用緩存功能
在啟動類上添加@EnableCaching
注解:
@SpringBootApplication @EnableCaching // 啟用緩存 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
4. 配置緩存管理器(可選但推薦)
自定義Redis緩存配置(如設(shè)置過期時間、序列化方式):
import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; @Configuration @EnableCaching public class RedisCacheConfig { @Bean public RedisCacheConfiguration cacheConfiguration() { return RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofMinutes(10)) // 默認緩存過期時間:10分鐘 .disableCachingNullValues() // 不緩存null值 .serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer( new GenericJackson2JsonRedisSerializer() // 使用JSON序列化 ) ); } }
5. 在Service層使用緩存注解
在需要緩存的方法上添加Spring Cache注解:
注解 | 作用 |
---|---|
@Cacheable | 查詢時優(yōu)先讀緩存,無緩存則執(zhí)行方法并保存結(jié)果 |
@CachePut | 每次執(zhí)行方法并更新緩存(常用于更新操作) |
@CacheEvict | 刪除緩存(常用于刪除或更新操作) |
示例代碼:
@Service public class UserService { // 根據(jù)ID查詢用戶(結(jié)果緩存到"users"區(qū)域,key為#id) @Cacheable(value = "users", key = "#id") public User getUserById(Long id) { // 模擬數(shù)據(jù)庫查詢 return userRepository.findById(id).orElse(null); } // 更新用戶信息(同時更新緩存) @CachePut(value = "users", key = "#user.id") public User updateUser(User user) { return userRepository.save(user); } // 刪除用戶(同時移除緩存) @CacheEvict(value = "users", key = "#id") public void deleteUser(Long id) { userRepository.deleteById(id); } // 清除"users"區(qū)域所有緩存(如批量更新后) @CacheEvict(value = "users", allEntries = true) public void clearAllUserCache() {} }
6. 驗證緩存效果
觀察日志:首次查詢會訪問數(shù)據(jù)庫,后續(xù)相同請求不會打印SQL。
Redis命令行檢查:
redis-cli > KEYS * # 查看所有緩存鍵 > GET "users::1" # 查看key為1的用戶緩存
強制刷新緩存:更新數(shù)據(jù)后,檢查緩存是否被清除/更新。
常見問題解決
序列化異常:
- 確保實體類實現(xiàn)
java.io.Serializable
接口。 - 使用JSON序列化(如
GenericJackson2JsonRedisSerializer
)。
- 確保實體類實現(xiàn)
緩存穿透:
- 對空結(jié)果也進行短時間緩存(需自定義配置)。
- 使用
@Cacheable
的unless
參數(shù):@Cacheable(value="users", unless="#result == null")
緩存一致性:
- 更新數(shù)據(jù)庫后立即清除或更新緩存(通過
@CachePut
/@CacheEvict
)。
- 更新數(shù)據(jù)庫后立即清除或更新緩存(通過
通過以上步驟,即可在Spring Boot中高效集成Redis實現(xiàn)緩存功能,顯著提升應(yīng)用性能。
到此這篇關(guān)于SpringBoot中集成Redis進行緩存的實現(xiàn)的文章就介紹到這了,更多相關(guān)SpringBoot集成Redis緩存內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
IDEA新建javaWeb以及Servlet簡單實現(xiàn)小結(jié)
這篇文章主要介紹了IDEA新建javaWeb以及Servlet簡單實現(xiàn)小結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-11-11使用JPA自定義VO類型轉(zhuǎn)換(EntityUtils工具類)
這篇文章主要介紹了使用JPA自定義VO類型轉(zhuǎn)換(EntityUtils工具類),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11關(guān)于spring版本與JDK版本不兼容的問題及解決方法
這篇文章主要介紹了關(guān)于spring版本與JDK版本不兼容的問題,本文給大家?guī)砹私鉀Q方法,需要的朋友可以參考下2018-11-11利用Spring boot如何創(chuàng)建簡單的web交互應(yīng)用
這篇文章主要介紹了利用Spring boot如何創(chuàng)建簡單的web交互應(yīng)用的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-04-04Spring與Mybatis整合方式(mybatis-spring整合jar包功能)
這篇文章主要介紹了Spring與Mybatis整合方式(mybatis-spring整合jar包功能),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-05-05springboot集成nacos實現(xiàn)自動刷新的示例代碼
研究nacos時發(fā)現(xiàn),springboot版本可使用@NacosValue實現(xiàn)配置的自動刷新,本文主要介紹了springboot集成nacos實現(xiàn)自動刷新的示例代碼,感興趣的可以了解一下2023-11-11