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連接工廠(chǎng)
@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)文章
Java中將String轉(zhuǎn)換為int的多種方法
字符串轉(zhuǎn)換為整數(shù)是一個(gè)常見(jiàn)需求,本文主要介紹了Java中將String轉(zhuǎn)換為int的多種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07
解決SpringBoot請(qǐng)求返回字符串中文亂碼的問(wèn)題
這篇文章主要介紹了解決SpringBoot請(qǐng)求返回字符串中文亂碼的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
finally 一定會(huì)執(zhí)行(實(shí)例代碼)
下面小編就為大家?guī)?lái)一篇finally 一定會(huì)執(zhí)行(實(shí)例代碼)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-07-07
Java網(wǎng)絡(luò)通信中ServerSocket的設(shè)計(jì)優(yōu)化方案
今天小編就為大家分享一篇關(guān)于Java網(wǎng)絡(luò)通信中ServerSocket的設(shè)計(jì)優(yōu)化方案,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-04-04
詳解Java 反射和反射的應(yīng)用場(chǎng)景
這篇文章主要介紹了Java 反射和反射的應(yīng)用場(chǎng)景的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)Java反射的相關(guān)知識(shí),感興趣的朋友可以了解下2020-08-08
一文快速了解spring?boot中的@idempotent注解
idempotence注解是RESTful API設(shè)計(jì)中一個(gè)重要的概念,它可以保證操作的可靠性和一致性,下面這篇文章主要給大家介紹了關(guān)于spring?boot中@idempotent注解的相關(guān)資料,需要的朋友可以參考下2024-01-01

