本篇文章小编给大家分享一下Redis存储对象代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
Redis存储对象
用的Jedis客户端
首先引入依赖
redis.clients jedis 3.2.0
创建一个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"); Listuser = 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* @Author 徐柯 * @Description 改写redistemplate序列化规则 * @Date 13:20 2021/5/20 * @Param [redisConnectionFactory] **/ @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate 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; } }