詳解SpringBoot如何使用Redis和Redis緩存
一、配置環(huán)境
首先,先創(chuàng)建一個SpringBoot項目,并且導(dǎo)入Redis依賴,使用Jedis進(jìn)行連接測試。
本人的Redis裝在虛擬機(jī)里,直接切換到虛擬機(jī)中的安裝目錄,啟動redis服務(wù),打開redis-cli,如果你設(shè)置了密碼,還要先輸入密碼。
cd redis安裝目錄 #啟動redis redis-server /etc/redis.conf #進(jìn)入redis redis-cli #如果你設(shè)置了密碼 auth 密碼
在項目中,設(shè)置配置文件
# mysql數(shù)據(jù)庫連接 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/redisdemo?serverTimezone=GMT%2B8 spring.datasource.username=root spring.datasource.password=123456 #返回json的全局時間格式 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8 #配置mapper xml文件的路徑 mybatis-plus.mapper-locations=classpath:com/rh/csdn_redis_demo/mapper/xml/*.xml #mybatis日志 mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl #配置redis spring.redis.host=你的redis地址 spring.redis.password=你的redis密碼(沒有直接空著,或者可以注掉這行) spring.redis.port=6379 spring.redis.database= 0 spring.redis.timeout=1800000 spring.redis.lettuce.pool.max-active=20 spring.redis.lettuce.pool.max-wait=-1 #最大阻塞等待時間(負(fù)數(shù)表示沒限制) spring.redis.lettuce.pool.max-idle=5 spring.redis.lettuce.pool.min-idle=0
在test中寫一個測試方法,測試是否能夠連接,返回值為pong
Jedis jedis = new Jedis("你的redis安裝的ip地址",6379); //沒有密碼就注掉這行,不然會報錯 jedis.auth("你的redis密碼");//設(shè)置密碼 String value = jedis.ping(); System.out.println(value);
二、Redis的基本操作
首先,要寫一個redisconfig的配置類,這個類是為了解決redis存取值的序列化問題和緩存問題。
@EnableCaching @Configuration public class RedisConfig extends CachingConfigurerSupport { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); RedisSerializer<String> redisSerializer = new StringRedisSerializer(); 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); template.setConnectionFactory(factory); //key序列化方式 template.setKeySerializer(redisSerializer); //value序列化 template.setValueSerializer(jackson2JsonRedisSerializer); //value hashmap序列化 template.setHashValueSerializer(jackson2JsonRedisSerializer); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { RedisSerializer<String> redisSerializer = new StringRedisSerializer(); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //解決查詢緩存轉(zhuǎn)換異常的問題 ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); // 配置序列化(解決亂碼的問題),過期時間600秒 RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() .entryTtl(Duration.ofSeconds(600)) //設(shè)置數(shù)據(jù)過期時間600秒 .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) .disableCachingNullValues(); RedisCacheManager cacheManager = RedisCacheManager.builder(factory) .cacheDefaults(config) .build(); return cacheManager; } }
定義一個controller,寫一個測試方法,進(jìn)行訪問
@RestController @RequestMapping("redisTest") public class RedisTestController { @Autowired private RedisTemplate redisTemplate; @GetMapping("/test01") public void test01(){ redisTemplate.opsForValue().set("test","redis存值測試"); String test = (String) redisTemplate.opsForValue().get("test"); System.out.println(test); } }
在reids中也可以查詢key與vaule(中文沒有顯示是shell的編碼問題)。
SpringBoot中進(jìn)行redis的操作基本都是借助于ops*,各位可以根據(jù)自己需求進(jìn)行其他的選用。
三、使用redis作緩存
簡單的用redis做一個緩存,這里使用@Cacheable在方法上作緩存。
寫一個用于訪問的test02方法,并在該方法上作緩存。
controller
@RestController @RequestMapping("redisTest") public class RedisTestController { @Autowired private RedisTemplate redisTemplate; @Autowired private UserService userService; @GetMapping("/test01") public void test01(){ redisTemplate.opsForValue().set("test","redis存值測試"); String test = (String) redisTemplate.opsForValue().get("test"); System.out.println(test); } @GetMapping("/test02") public List<User> test02(){ List<User> userList = userService.test02(); System.out.println(userList); return null; } }
service
@Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Cacheable(value = "user",key = "'cache'") @Override public List<User> test02() { List<User> userList = baseMapper.selectList(null); return userList; } }
首先查看redis中緩存內(nèi)容
然后調(diào)用方法
可以看到,這一次查詢,由于redis中沒有緩存,所以對數(shù)據(jù)庫進(jìn)行了訪問,再次查看redis中key
可以看到redis中多出了user::cache這個鍵,這個就是我們做的緩存了(編碼格式問題導(dǎo)致這么顯示)
這個時候我們再次訪問方法
可以看到,第二次調(diào)用方法,并沒有連接數(shù)據(jù)庫,沒有操作數(shù)據(jù)庫的語句,這表示我們成功的從緩存中取出了數(shù)據(jù)。
tpis.
如果你在連接redis的時候出現(xiàn)了MISCONF Redis is configured to save RDB snapshots……這樣的錯誤提示,這表示redis的持久化失效了,可以再redis-cli中直接輸入config set stop-writes-on-bgsave-error no,但是這種方法不能永遠(yuǎn)解決這個問題,如果需要永解決這個問題,可以搜索redis持久化失效的解決方法。
以上就是詳解SpringBoot如何使用Redis和Redis緩存的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot使用Redis 緩存的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
springboot實現(xiàn)異步調(diào)用@Async的示例
這篇文章主要介紹了springboot實現(xiàn)異步調(diào)用@Async的示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12SpringBoot返回統(tǒng)一的JSON標(biāo)準(zhǔn)格式實現(xiàn)步驟
這篇文章主要介紹了SpringBoot返回統(tǒng)一的JSON標(biāo)準(zhǔn)格式,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08springboot 返回json格式數(shù)據(jù)時間格式配置方式
這篇文章主要介紹了springboot 返回json格式數(shù)據(jù)時間格式配置方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11springBoot controller,service,dao,mapper,model層的作用說明
這篇文章主要介紹了springBoot controller,service,dao,mapper,model層的作用說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11java整數(shù)與byte數(shù)組的轉(zhuǎn)換實現(xiàn)代碼
這篇文章主要介紹了java整數(shù)與byte數(shù)組的轉(zhuǎn)換實現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-07-07深入解析Java的Servlet過濾器的原理及其應(yīng)用
這篇文章主要介紹了深入解析Java的Servlet過濾器的原理及應(yīng)用,Java編寫的Servlet通常是一個與網(wǎng)頁一起作用于瀏覽器客戶端的程序,需要的朋友可以參考下2016-01-01