SpringBoot集成Redis流程詳解
第一步,導(dǎo)入jar包
<!--Redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--Redis-->
第二步,編寫配置類
這是一個使用FastJson序列化器,配置RedisTemplate的Spring Bean的Java類。該類使用了@Configuration注釋來標識這是一個配置類,并使用@Bean注釋來標識該方法是創(chuàng)建一個Bean的工廠方法。該方法名為redisTemplate,并使用了@ConditionalOnMissingBean注釋,表示如果在上下文中沒有StringRedisTemplate類型的Bean,則會自動創(chuàng)建一個該類型的Bean。該方法返回一個RedisTemplate類型的對象,該對象被配置為使用FastJson序列化器,以便將對象序列化為JSON格式進行存儲和檢索。在方法內(nèi)部,通過setConnectionFactory方法設(shè)置了RedisTemplate的連接工廠,并通過setKeySerializer和setValueSerializer方法設(shè)置了鍵和值的序列化器。此外,該類還提供了一個名為stringRedisTemplate的方法,用于創(chuàng)建StringRedisTemplate類型的Bean。
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { /** * 重寫Redis序列化方式,使用Json方式: * 當我們的數(shù)據(jù)存儲到Redis的時候,我們的鍵(key)和值(value) * 都是通過Spring提供的Serializer序列化到數(shù)據(jù)庫的。RedisTemplate默認使用的是JdkSerializationRedisSerializer, * StringRedisTemplate默認使用的是StringRedisSerializer。 * Spring Data JPA為我們提供了下面的Serializer: * GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、 * JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。 * 在此我們將自己配置RedisTemplate并定義Serializer。 * * @param redisConnectionFactory * @return */ @Bean("getRedisTemplate") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); /** * 配置連接工廠 */ redisTemplate.setConnectionFactory(redisConnectionFactory); /** * 使用FJackson2JsonRedisSerializer序列化工具 */ FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); /** * 指定要序列化的域Field、set、get,以及修飾符范圍 * ANY是都有,包括private、public */ objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); /** * 指定序列化輸入的類型,類必須是非final修飾的, * final修飾的類,比如 * public final class User implements Serializable{},會包異常 */ objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY); /** *設(shè)置鍵(key)的序列化采用StringRedisSerializer。 */ redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); /** * 設(shè)置值(value)的序列化采用jackson2JsonRedisSerializer。 */ redisTemplate.setValueSerializer(fastJsonRedisSerializer); redisTemplate.setHashValueSerializer(fastJsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } /** * 配置stringRedisTemplate序列化方式 * * @param redisConnectionFactory * @return */ @Bean @ConditionalOnMissingBean(StringRedisTemplate.class) public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; } }
第三步,編寫util類
這段代碼是一個基于Spring框架和Redis實現(xiàn)的工具類,封裝了一些常見的操作方法。它依賴于另一個Redis配置類,通過@Autowired注解和@Qualifier注解來獲取到RedisTemplate實例,從而進行操作。
具體的操作方法有:
- set:設(shè)置鍵值對,將value存儲到key中。
- set:設(shè)置鍵值對并指定過期時間,將value存儲到key中,并設(shè)置過期時間。
- remove:刪除一個或多個key對應(yīng)的值。
- exists:判斷指定的key是否存在于緩存中。
- get:獲取指定key對應(yīng)的值。
需要注意的是,get方法返回的是一個經(jīng)過JSON序列化的字符串,而不是原始的對象。如果要使用對象,需要在調(diào)用get方法之后進行反序列化。
package com.wangfugui.apprentice.common.util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import java.io.Serializable; import java.util.concurrent.TimeUnit; /** * RedisUtils:redis工具類 */ @Component public class RedisUtils { @Autowired @Qualifier("getRedisTemplate") private RedisTemplate redisTemplate; /** * 設(shè)置鍵值 * * @Param: [key, value] * @return: boolean * @Author: MaSiyi * @Date: 2021/11/20 */ public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 寫入緩存設(shè)置失效時間 * * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } /** * 批量刪除對應(yīng)的value */ public void remove(final String... keys) { for (String key : keys) { remove(key); } } /** * 刪除對應(yīng)的value */ public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } /** * 判斷緩存當中是否有對應(yīng)的value * * @param key * @return */ public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 根據(jù)key,獲取到對應(yīng)的value值 * * @param key * key-value對應(yīng)的key * @return 該key對應(yīng)的值。 * 注: 若key不存在, 則返回null。 * * @date 2020/3/8 16:27:41 */ public String get(String key) { return JSONObject.toJSONString(redisTemplate.opsForValue().get(key)); } }
第四步,配置yml
這是一個YAML格式的Spring Boot配置文件,配置了Redis數(shù)據(jù)庫的連接信息,包括:
- database: Redis數(shù)據(jù)庫的編號,默認為0。
- host: Redis服務(wù)器的IP地址。
- port: Redis服務(wù)器的端口號。
這些配置信息會被Spring Boot自動加載并注入到對應(yīng)的Bean中,可以在代碼中使用這些Bean來連接和操作Redis數(shù)據(jù)庫。
spring: redis: database: 0 host: 127.0.0.1 port: 6379
好了,就是這么的簡單,完整代碼請移至SpringBoot+Redis查看
以上就是SpringBoot集成Redis流程詳解的詳細內(nèi)容,更多關(guān)于SpringBoot集成Redis的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android開發(fā)中Socket通信的基本實現(xiàn)方法講解
這篇文章主要介紹了Android開發(fā)中Socket通信的基本實現(xiàn)方法講解,是安卓上移動互聯(lián)網(wǎng)程序開發(fā)的基礎(chǔ),需要的朋友可以參考下2015-12-12使用Spring Boot搭建Java web項目及開發(fā)過程圖文詳解
這篇文章主要介紹了使用Spring Boot搭建Java web項目及開發(fā)過程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06Spring?Boot監(jiān)控SQL運行情況的全過程
這篇文章主要給大家介紹了關(guān)于Spring?Boot監(jiān)控SQL運行情況的相關(guān)資料,文中通過實例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用SpringBoot具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2022-02-02Springboot+Vue+axios實現(xiàn)文章收藏功能
這篇文章主要為大家詳細介紹了Springboot+Vue+axios實現(xiàn)文章收藏功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-08-08