springboot中使用redis的方法代碼詳解
特別說(shuō)明:
本文針對(duì)的是新版 spring boot 2.1.3,其 spring data 依賴(lài)為 spring-boot-starter-data-redis
,且其默認(rèn)連接池為 lettuce
redis 作為一個(gè)高性能的內(nèi)存數(shù)據(jù)庫(kù),如果不會(huì)用就太落伍了,之前在 node.js 中用過(guò) redis,本篇記錄如何將 redis 集成到 spring boot 中。提供 redis 操作類(lèi),和注解使用 redis 兩種方式。主要內(nèi)容如下:
•docker 安裝 redis
•springboot 集成 redis
•編寫(xiě) redis 操作類(lèi)
•通過(guò)注解使用 redis
安裝 redis
通過(guò) docker 安裝,docker compose 編排文件如下:
# docker-compose.yml version: "2" services: redis: container_name: redis image: redis:3.2.10 ports: - "6379:6379"
然后在docker-compose.yml
所在目錄使用docker-compose up -d
命令,啟動(dòng) redis。
集成 springboot
說(shuō)明:springboot 版本為 2.1.3
添加 maven 依賴(lài)
只需添加spring-boot-starter-data-redis依賴(lài)即可,并排除 lettuce 依賴(lài),然后引入 jedis 和 jedis 的依賴(lài) commons-pool2
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
編寫(xiě) springboot 配置文件
配置文件如下:
server: port: 8081 servlet: context-path: /sso spring: application: name: SSO cache: type: redis redis: database: 0 host: 192.168.226.5 port: 6379 # 有密碼填密碼,沒(méi)有密碼不填 password: # 連接超時(shí)時(shí)間(ms) timeout: 1000ms # 高版本springboot中使用jedis或者lettuce jedis: pool: # 連接池最大連接數(shù)(負(fù)值表示無(wú)限制) max-active: 8 # 連接池最大阻塞等待時(shí)間(負(fù)值無(wú)限制) max-wait: 5000ms # 最大空閑鏈接數(shù) max-idle: 8 # 最小空閑鏈接數(shù) min-idle: 0
編寫(xiě)配置類(lèi)
配置類(lèi)代碼如下:
@EnableCaching//開(kāi)啟緩存 @Configuration public class RedisConfig extends CachingConfigurerSupport { /** * 設(shè)置緩存管理器,這里可以配置默認(rèn)過(guò)期時(shí)間等 * * @param connectionFactory 連接池 * @return */ @Bean public CacheManager cacheManager(RedisConnectionFactory connectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration .defaultCacheConfig() .entryTtl(Duration.ofSeconds(60)); //注意:請(qǐng)勿使用先new 配置對(duì)象,然后在調(diào)用entryTtl方法的方式來(lái)操作 //會(huì)導(dǎo)致配置不生效,原因是調(diào)用.entryTtl方法會(huì)返回一個(gè)新的配置對(duì)象,而不是在原來(lái)的配置對(duì)象上修改 RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory); RedisCacheManager manager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration); return manager; } @SuppressWarnings("all") @Bean public RedisTemplate<String, String> redisTemplate(JedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); RedisSerializer stringSerializer = new StringRedisSerializer(); template.setKeySerializer(stringSerializer); template.setValueSerializer(jackson2JsonRedisSerializer); template.setHashKeySerializer(stringSerializer); template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } //使用jedis連接池建立jedis連接工廠 @Bean public JedisConnectionFactory jedisConnectionFactory() { logger.info("jedisConnectionFactory:初始化了"); JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(maxIdle); config.setMinIdle(minIdle); config.setMaxWaitMillis(maxWaitMillis); config.setMaxTotal(maxActive); //鏈接耗盡時(shí)是否阻塞,默認(rèn)true config.setBlockWhenExhausted(true); //是否啟用pool的jmx管理功能,默認(rèn)true config.setJmxEnabled(true); JedisConnectionFactory factory = new JedisConnectionFactory(); factory.setPoolConfig(config); factory.setHostName(host); factory.setPort(port); factory.setPassword(password); factory.setDatabase(database); factory.setTimeout(timeout); return factory; } }
使用方法
有兩種方法來(lái)進(jìn)行緩存操作,一種是在方法上添加緩存注解實(shí)現(xiàn)各種操作,一種是手動(dòng)控制。個(gè)人比較喜歡手動(dòng)控制,覺(jué)得這樣都在自己的掌控中。
通過(guò)注解使用
主要有以下 5 個(gè)注解:
•@CacheConfig: 類(lèi)級(jí)別緩存,設(shè)置緩存 key 前綴之類(lèi)的
•@Cacheable: 觸發(fā)緩存入口
•@CacheEvict: 觸發(fā)移除緩存
•@CachePut: 更新緩存
•@Caching: 組合緩存
@CacheConfig
該注解可以將緩存分類(lèi),它是類(lèi)級(jí)別注解,主要用于給某個(gè)類(lèi)的緩存全局配置,例子如下:
@CacheConfig(cacheNames = "redis_test") @Service public class RedisService { //.... }
上面 CacheConfig 會(huì)給類(lèi)下通過(guò)注解生成的 key 加上 redis_test
的前綴。
@Cacheable
方法級(jí)別注解,根據(jù) key 查詢(xún)緩存:
•如果 key 不存在,將方法返回值緩存到 redis 中
•如果 key 存在,直接從緩存中取值
例子如下:
/** * 緩存時(shí)間,首次查詢(xún)后會(huì)緩存結(jié)果,key中的值可使用表達(dá)式計(jì)算. * 如不提供key,將使用默認(rèn)key構(gòu)造方法生成一個(gè)key * @return long */ @Cacheable(key = "'currentTime'") public long getTime() { return System.currentTimeMillis(); }
多次調(diào)用此段代碼會(huì)發(fā)現(xiàn)每次返回的值都是一樣的。
CachePut
用于更新緩存,每次調(diào)用都會(huì)想 db 請(qǐng)求,緩存數(shù)據(jù)
•如果 key 存在,更新內(nèi)容
•如果 key 不存在,插入內(nèi)容
代碼如下:
/** * 一般用于更新查插入操作,每次都會(huì)請(qǐng)求db */ @CachePut(key = "'currentTime'+#id") public long updateTime(String id) { return System.currentTimeMillis(); }
每次調(diào)用此方法都會(huì)根據(jù) key 刷新 redis 中的緩存數(shù)據(jù)。
@CacheEvict
根據(jù) key 刪除緩存中的數(shù)據(jù)。allEntries=true
表示刪除緩存中所有數(shù)據(jù)。
代碼如下:
@CacheEvict(key = "'currentTime'+#id",allEntries=false) public void deleteTime(String id) { }
@Caching
本注解可將其他注解組合起來(lái)使用。比如下面的例子:
//value屬性為key指定前綴 @Caching(put = {@CachePut(value = "user", key = "'name_'+#user.name"), @CachePut(value = "user", key = "'pass_'+#user.password")}) public User testCaching(User user) { return user; }
上面的代碼執(zhí)行后將在 redis 中插入兩條記錄。使用keys *
將看到如下結(jié)果:
手動(dòng)控制
手動(dòng)控制就相當(dāng)于 mybatis 的手寫(xiě) sql 語(yǔ)句,需要調(diào)用redisTemplate
中的各種方法來(lái)進(jìn)行緩存查詢(xún),緩存更新,緩存刪除等操作。
使用方法參見(jiàn) util/RedisUtil 中的方法。redisTemplate
基本可以實(shí)現(xiàn)所有的 redis 操作。
總結(jié)
以上所述是小編給大家介紹的springboot中使用redis的方法代碼詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
- SpringBoot項(xiàng)目中使用redis緩存的方法步驟
- 詳解springboot中redis的使用和分布式session共享問(wèn)題
- SpringBoot+Mybatis項(xiàng)目使用Redis做Mybatis的二級(jí)緩存的方法
- SpringBoot使用Redisson實(shí)現(xiàn)分布式鎖(秒殺系統(tǒng))
- SpringBoot中Shiro緩存使用Redis、Ehcache的方法
- Redis在springboot中的使用教程
- Springboot使用redis進(jìn)行api防刷限流過(guò)程詳解
- SpringBoot使用Redis緩存的實(shí)現(xiàn)方法
- springboot中使用redis由淺入深解析
- SpringBoot中使用Redis的完整實(shí)例
相關(guān)文章
SpringBoot2.3定制錯(cuò)誤頁(yè)面的方法示例
這篇文章主要介紹了SpringBoot2.3定制錯(cuò)誤頁(yè)面的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08java.io.IOException:你的主機(jī)中的軟件中止了一個(gè)已建立的連接踩坑實(shí)戰(zhàn)
最近在工作中遇到了個(gè)問(wèn)題,分享給同樣遇到問(wèn)題的同學(xué),這篇文章主要給大家介紹了關(guān)于java.io.IOException:你的主機(jī)中的軟件中止了一個(gè)已建立的連接的踩坑實(shí)戰(zhàn)記錄,需要的朋友可以參考下2023-03-03springboot中報(bào)錯(cuò)Invalid character found in
這篇文章主要介紹了springboot中報(bào)錯(cuò)Invalid character found in the request的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09Java 多線程并發(fā)編程_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了Java 多線程并發(fā)編程的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-05-05SpringCloud中的Eureka注冊(cè)中心詳細(xì)解讀
這篇文章主要介紹了SpringCloud中的Eureka注冊(cè)中心詳細(xì)解讀,想要參與服務(wù)注冊(cè)發(fā)現(xiàn)的實(shí)例首先需要向Eureka服務(wù)器注冊(cè)信息,注冊(cè)在第一次心跳發(fā)生時(shí)提交,需要的朋友可以參考下2023-11-11Springboot+ElementUi實(shí)現(xiàn)評(píng)論、回復(fù)、點(diǎn)贊功能
這篇文章主要介紹了通過(guò)Springboot ElementUi實(shí)現(xiàn)評(píng)論、回復(fù)、點(diǎn)贊功能。如果是自己評(píng)論的還可以刪除,刪除的規(guī)則是如果該評(píng)論下還有回復(fù),也一并刪除。需要的可以參考一下2022-01-01java使用@Scheduled注解執(zhí)行定時(shí)任務(wù)
這篇文章主要給大家介紹了關(guān)于java使用@Scheduled注解執(zhí)行定時(shí)任務(wù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01詳解Spring數(shù)據(jù)緩存注解@Cacheable、@CachePut、@CacheEvict
這篇文章主要介紹了詳解Spring數(shù)據(jù)緩存注解@Cacheable、CachePut、@CacheEvict,當(dāng)以一組參數(shù)第一次調(diào)用某個(gè)方法時(shí),返回值會(huì)被保存在緩存中,如果這個(gè)方法再次以相同的參數(shù)進(jìn)行調(diào)用時(shí),這個(gè)返回值會(huì)從緩存中查詢(xún)獲取,需要的朋友可以參考下2023-07-07SpringBoot圖文并茂詳解如何引入mybatis與連接Mysql數(shù)據(jù)庫(kù)
這篇文章主要介紹了SpringBoot如何引入mybatis與連接Mysql數(shù)據(jù)庫(kù),本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-07-07