Redis如何存儲對象

Redis存儲對象

在以往面試中,多次被問到Redis怎麼存儲對象,我支支吾吾半天回答不上來,畢竟我隻用過String類型,為瞭避免以後的尷尬,今天花點時間來整理一下。

本人用的Jedis客戶端

首先引入依賴

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>

創建一個Jedis實例

package com.xiateng.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
 
/**
 * jedis獲取工具類
 */
public class JedisUtil { 
    private static JedisPool jedisPool;
    private static final Logger logger = LoggerFactory.getLogger(JedisUtil.class);
 
    static {
        // 初始化連接池
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(20);
        jedisPoolConfig.setMaxIdle(10);
        jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
        logger.info("jedisPool連接池初始化====" + jedisPool);
    }
 
    /**
     * 獲取一個Jedis實例
     * @return
     */
    public synchronized static Jedis getJedis(){
        Jedis jedis = jedisPool.getResource();
//        jedis.auth("123456");//密碼
        return jedis;
    }
}

下面我們來實現存儲對象

方式一:將對象轉化為JSON字符串存入redis

Jedis jedis = JedisUtil.getJedis();
TUser tUser = new TUser();
tUser.setUserName("你好");
tUser.setPassword("2342342");
jedis.set("xiateng", JSON.toJSONString(tUser));
 
String sss = jedis.get("xiateng");
TUser ssss = JSON.parseObject(sss,TUser.class);
jedis.del("xiateng");
System.out.println("---------------------------:  "+ssss.toString());

方式二:將對象序列化後存到redis

封裝序列化跟反序列化方法

package com.xiateng.util; 
import java.io.*; 
public class SerializeUtil {
 
    /**
     * 序列化操作
     * @param object
     * @return
     */
    public static byte[] serialize(Object object){
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
 
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return null;
    }
 
    /**
     * 反序列化操作
     * @param bytes
     * @return
     */
    public static Object unSerialize(byte[] bytes){
        ByteArrayInputStream bais = null;
 
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
 
        return null;
    }
}

保存對象

Jedis jedis = JedisUtil.getJedis();      
jedis.set("code".getBytes(), SerializeUtil.serialize(tUser));
byte[] bytes = jedis.get("code".getBytes());
TUser o = (TUser)SerializeUtil.unSerialize(bytes);
jedis.del("code");
System.out.println(o.toString());

方式三:將對象用Hash數據類型存儲

Jedis jedis = JedisUtil.getJedis();
jedis.hset("user", "id", "3");
jedis.hset("user", "name", "xiateng");
jedis.hset("user", "password", "123455");
jedis.hget("user","id");
List<String> user = jedis.hmget("user", new String[]{"id","name","password"});
System.out.println("---------------------------:  "+user);
 
// 輸出結果 [3,xiateng,123455]

註意:以序列化的方式存儲的對象需要實現 Serializable 接口

Redis可以存儲java對象嗎

答案:是可以

但是你對象必須要序列化。

redis沒有辦法把一個沒有序列化的對象存儲到redis中。

package com.kuangstudy.entiy;
import lombok.Data;
public class User implements java.io.Serializable{
    private Integer id;
    private String nickname;
    private String password;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getNickname() {
        return nickname;
    }
    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

這樣太麻煩瞭,並且存儲中文會有亂碼,那如何解決呢?隻能重新定義一個redisTemplate

package com.kuangstudy.config;
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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfiguration {
    /**
     * @return org.springframework.data.redis.core.RedisTemplate<java.lang.String, java.lang.Object>
     * @Author 徐柯
     * @Description 改寫redistemplate序列化規則
     * @Date 13:20 2021/5/20
     * @Param [redisConnectionFactory]
     **/
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 創建一個json的序列化方式
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        // 設置value用jackjson進行處理
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 設置key用string序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: