Spring-boot集成Redis


pom文件

        <!-- springboot整合redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <version>2.5.6</version>
        </dependency>

配置類

Redisconfig

package com.eagle.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @Author LiGuangLong
 * @Date 2021-11-01 9:58
 * @Version 1.0
 **/
@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        //設置工廠鏈接
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //設置自定義序列化方式
        setSerializeConfig(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }
    private void setSerializeConfig(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory redisConnectionFactory) {
        //對字符串采取普通的序列化方式 適用於key 因為我們一般采取簡單字符串作為key
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //普通的string類型的key采用 普通序列化方式
        redisTemplate.setKeySerializer(stringRedisSerializer);
        //普通hash類型的key也使用 普通序列化方式
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //解決查詢緩存轉換異常的問題  大家不能理解就直接用就可以了 這是springboot自帶的jackson序列化類,但是會有一定問題
        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);
        //普通的值采用jackson方式自動序列化
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        //hash類型的值也采用jackson方式序列化
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        //屬性設置完成afterPropertiesSet就會被調用,可以對設置不成功的做一些默認處理
        redisTemplate.afterPropertiesSet();
    }

}


備注: 可以避免序列化對象

如果不進行自定義序列化存放的key和value都是默認序列化(16進制數據) java中進行取得時候會默認反序列化

如果進行了自定義序列化 取值得時候進行判斷會出錯

所以現在存入數據的時候轉為String 取得時候在吧 String 轉為json對象

net.sf.json
JSONArray.fromObject(list).toString()   //list轉字符串 list<e> 可以是對象
JSONArray.fromObject(redis.get("sfzxx"))  // 獲取 給對象沒什么區別就是 swagger 沒有提示了
    
    
jsonObject.toString()   //存
JSONObject.fromObject(redis.get("dpdtsj")); // 取

雖然不太好但是也可以用

使用阿里巴巴的json庫可以解決swagger問題

JSON.toJSONString(list)    //list<dto> list<dto>轉字符串存入
List<TollStation> list =JSON.parseArray(redis.get("sfzxx"),TollStation.class);   //取 並提供list中對象的類型 

String s = JSON.toJSONString(user);//dto轉字符串
User user1 = JSON.parseObject(s, User.class);
String b="["+s+"]";
List<User> users = JSON.parseArray(b, User.class);   //字符串轉 list<dto>

工具類

package com.eagle.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author LiGuangLong
 * @Date 2021-11-01 10:18
 * @Version 1.0
 **/
@SuppressWarnings("ALL")
@Component
@Slf4j
public class RedisUtils {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    public String get(String key){
        return  key == null ? null : (String) redisTemplate.opsForValue().get(key);
    }
    public Object getObject(String key){
        return  key == null ? null : redisTemplate.opsForValue().get(key);
    }
    public void set(String key,Object value){
        redisTemplate.opsForValue().set(key,value);
    }

    /**
     *本來只可以放入string類型,但是我們配置了自動序列化所以這兒可以傳入object
     */
    public void setex(String key,Object value,long expire){
        redisTemplate.opsForValue().set(key,value,expire, TimeUnit.SECONDS);
    }
    public  <T> List<T> ObjectToList(Object obj, Class<T> clazz){
        List<T> result = new ArrayList<T>();
        if(obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                result.add(clazz.cast(o));
            }
            return result;
        }
        return null;
    }
    public String ObjectToString(Object obj){
        return JSON.toJSONString(obj);
    }
    public <T> T StringToObject(String text, Class<T> clazz) {
        return JSON.parseObject(text, clazz);
    }
    public <T> List<T> StringToList(String text, Class<T> clazz) {
        return JSON.parseArray(text, clazz);
    }
    /**
     *判斷key是否存在
     */
    public boolean exists(String key){
        return redisTemplate.hasKey(key);
    }

    public boolean expire(String key,long expire){
        return redisTemplate.expire(key,expire,TimeUnit.SECONDS);
    }


    /**
     *查看key過期時間
     */
    public long ttl(String key){
        return redisTemplate.getExpire(key);
    }
    public void del(String ...keys){
        if(keys!=null&&keys.length>0) {
            redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(keys));
        }
    }
    public long incrBy(String key,long step){
        return redisTemplate.opsForValue().increment(key,step);
    }
    public boolean setnx(String key,Object value){
        return redisTemplate.opsForValue().setIfAbsent(key,value);
    }
    public boolean setnxAndExpire(String key,Object value,long expire){
        return redisTemplate.opsForValue().setIfAbsent(key,value,expire,TimeUnit.SECONDS);
    }
    public Object getAndSet(String key,Object value){
        return redisTemplate.opsForValue().getAndSet(key,value);
    }
}


對於接口請求慢的可以 放入redis 並設置超時時間

取得時候判斷下

!redis.exists(key)

set的時候建議設置過期時間

json轉換

image-20211102155554641

object轉

image-20211102161532659


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM