使用redis存储对象或集合时,不能直接存储。需要将对象或集

合通过序列化转换为可存储的json,这里使用了fastjson来转型

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、

zset(sorted set --有序集合)和hash(哈希类型)

所用到的依赖,可以在maven仓库中查找

<!-- redis客户端:Jedis -->
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId><version>2.7.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version>
</dependency>

1.redis工具类,里面写了部分redis常用命令

package com.bcc.util;import java.util.List;
import java.util.Map;
import java.util.Set;import org.apache.commons.lang.StringUtils;import com.fasterxml.jackson.databind.ObjectMapper;import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.util.SafeEncoder;public class jedisUtil {private static String HOST = "localhost";private static int PORT = 6379;private static JedisPool pool = null;static {JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(128);config.setMaxIdle(80);config.setMaxWaitMillis(2001);pool = new JedisPool(config, HOST, PORT, 2000);}/*** 把key存入redis中** @param key     k* @param value   v* @param seconds 过期时间(秒)* @return boolean*/public static boolean set(byte[] key, byte[] value, int seconds) {Jedis jedis = null;try {jedis = pool.getResource();String result = jedis.set(key, value);if (seconds > 0) {Long r = jedis.expire(key, seconds);}} catch (Exception e) {return false;} finally {if (null != jedis) {jedis.close();}}return true;}public static byte[] get(byte[] key) {byte[] value = null;Jedis jedis = null;try {jedis = pool.getResource();value = jedis.get(key);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return value;}/*** 向缓存中设置对象** @param key key* @param obj value* @return boolean*/public static boolean set(String key, Object obj, Integer seconds) {Jedis jedis = null;try {jedis = pool.getResource();ObjectMapper mapper = new ObjectMapper();String value = mapper.writeValueAsString(obj);jedis.set(SafeEncoder.encode(key), SafeEncoder.encode(value));if (seconds != null) {jedis.expire(key, seconds);}return true;} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return false;}/*** 向缓存中设置对象** @param key   key* @param value value* @return boolean*/public static boolean set(String key, String value, Integer seconds) {Jedis jedis = null;try {jedis = pool.getResource();jedis.set(SafeEncoder.encode(key), SafeEncoder.encode(value));if (seconds != null) {jedis.expire(key, seconds);}return true;} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return false;}/*** 移除缓存中设置对象** @param keys 被删除的KEYS* @return Long 被删除个数*/public static Long del(String... keys) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.del(keys);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}/*** 根据key 获取对象** @param key key* @return T*/public static <T> T get(String key, Class<T> clazz) {Jedis jedis = null;try {jedis = pool.getResource();String v = jedis.get(key);if (StringUtils.isNotEmpty(v)) {ObjectMapper mapper = new ObjectMapper();return mapper.readValue(v, clazz);}} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}/*** 根据key值得到String类型的返回值** @param key key* @return String*/public static String get(String key) {Jedis jedis = null;try {jedis = pool.getResource();String v = jedis.get(key);if (StringUtils.isNotEmpty(v)) {return v;}} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}public static Boolean exists(String key) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.exists(key);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}/*** redis的list操作:* 把元素插入到列表的尾部** @param key     KEY* @param strings 要插入的值,变参* @return 返回插入后list的大小*/public static Long rpush(String key, String... strings) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.rpush(key, strings);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}/*** redis的list操作:* 根据开始与结束下标取list中的值** @param key   KEY* @param start 开始下标* @param end   结束下标* @return List<String>*/public static List<String> lrange(String key, int start, int end) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.lrange(key, start, end);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}/*** redis的list操作:* 取列表的长度** @param key key* @return Long*/public static Long llen(String key) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.llen(key);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}/*** redis的list操作:* 根据值移除list中的元素** @param key   KEY* @param count :*              count > 0 : 从表头开始向表尾搜索,移除与 value 相等的元素,数量为 count 。*              count < 0 : 从表尾开始向表头搜索,移除与 value 相等的元素,数量为 count 的绝对值。*              count = 0 : 移除表中所有与 value 相等的值。* @param value 要删除的值* @return 返回被移除的个数*/public static Long lrem(String key, long count, String value) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.lrem(key, count, value);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}public static boolean setLong(String key, Long value) {Jedis jedis = null;try {jedis = pool.getResource();return "OK".equals(jedis.set(key, String.valueOf(value)));} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return false;}public static Long getLong(String key) {String result = get(key);return result == null ? null : Long.valueOf(result);}public static Long incrBy(String key, Long increment) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.incrBy(key, increment);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}public static Long hashSet(String key, String field, String value) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.hset(key, field, value);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return -1L;}public static Long hashSetLong(String key, String field, Long value) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.hset(key, field, String.valueOf(value));} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return -1L;}public static Long hashIncrBy(String key, String field, Long increment) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.hincrBy(key, field, increment);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return -1L;}public static Map<String, String> hashGetAll(String key) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.hgetAll(key);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}public static Set<String> hashKeys(String key) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.hkeys(key);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}public static Long hashDelAll(String key, String... fields) {Jedis jedis = null;try {jedis = pool.getResource();return jedis.hdel(key, fields);} catch (Exception e) {} finally {if (null != jedis) {jedis.close();}}return null;}
}

2.实现类中调用

package com.bcc.service;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcc.dao.usermapper;
import com.bcc.pojo.City;
import com.bcc.util.jedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class userserviceimpl implements userservice{@Autowiredprivate usermapper um;//这里展示一个简单的查询方法,返回的是list集合,把list集合存入redis@Overridepublic List<City> listCity(String sname) {//首先先判断redis中是否存在该key值String aa1 = jedisUtil.get("aoo");if (aa1==null){ //若不存在首先走一下方法,从数据库中查询数据List<City> cities  = um.listCity(sname);//然后调用JSON.toJSONString()方法转为jsonString ss = JSON.toJSONString(cities);//存入redisjedisUtil.set("aoo", ss, 10000*100000);return cities;}else {//若存在,将key值查询出来,此时的key值还是json形式String aoo = jedisUtil.get("aoo");//调用JSON.parseArray()方法转为list集合List<City> cities = JSON.parseArray(aoo,City.class);//JSON.parseObject方法是转为对象/*City city = JSON.parseObject(aoo, City.class);*/return cities;}}
}

redis存储对象和集合相关推荐

  1. Redis 存储对象信息是用 Hash 还是 String

    Redis 内部使用一个 RedisObject 对象来表示所有的 key 和 value,RedisObject 中的 type,则是代表一个 value 对象具体是何种数据类型,它包含字符串(St ...

  2. redis存储对象(通过JSON方式)

    redis存储对象 在Java程序中,redis提供的方法插入的key,value要么是string,要么就是byte[]数组.那如果是要插入的value是个对象怎么办呢?网上的方法大多是对这个对象进 ...

  3. redis储存实体类对象_Redis如何存储对象与集合示例详解

    前言 大家都知道在项目中,缓存以及mq消息队列可以说是不可或缺的2个重要技术.前者主要是为了减轻数据库压力,大幅度提升性能.后者主要是为了提高用户的体验度,我理解的是再后端做的一个ajax请求(异步) ...

  4. redis存储对象_redis内存优化总结

    本文主要参考<>一书,主要分为以下六个部分: 1.redisObject对象 2.缩减键值对象 3.共享对象池 4.字符串优化 5.编码优化 6.控制key的数量 一. redisObje ...

  5. Java操作Redis存储对象类型数据

    背景描述 关于JAVA去操作Redis时,如何存储一个对象的数据,这是大家非常关心的问题,虽然官方提供了存储String,List,Set等等类型,但并不满足我们现在实际应用.存储一个对象是非常常见的 ...

  6. Redis存储对象的三种方式

    存储对象的三种方式分别为: 1.将对象序列化后保存到Redis 2.将对象用FastJSON转为JSON字符串后存储 3.将对象用Hash数据类型存储 序列化工具类SerializeUtil publ ...

  7. redis存储二进制对象 python_python redis存储对象

    往往我们存放redis的时候都是字符串,可有时候我们也想存储对象怎么办? 首先我们构造对象:class Duankeke(object): def keke(self): print 33333下面演 ...

  8. 使用redis存储对象,取对象时的一些常见异常

    自动装配失败报空指针异常 报错: java.lang.NullPointerExceptionat com.example.service.UserServiceImpl.sendMsg(UserSe ...

  9. 【Redis】redis 存储对象 的三种方式

    1.概述 转载:https://blog.csdn.net/u014756827/article/details/88830973 2.方式一:序列化操作 public class Serialize ...

最新文章

  1. netty tcp服务端主动断开客户端_【Netty】服务端和客户端
  2. N900 Dual boot(meego maemo)
  3. hadoop分布式搭建
  4. python 递归方式实现斐波那契数列
  5. windows快捷键,photoshop快捷键,qq快捷键
  6. windows环境下Apache+PHP+MySQL搭建服务器
  7. Python 快速入门
  8. springmvc php,SpringMVC 常用注解
  9. 为什么我不推荐你使用vue-cli创建脚手架?
  10. JavaScript实现模糊推荐的input框(类似百度搜索框)
  11. 服务器来料检测作用,元器件的来料检测需要检测哪些方面
  12. 修改antd下拉框样式
  13. OpenCV之图像伪彩色增强
  14. Linux用户家目录与根目录
  15. 两个高斯分布乘积的理论推导
  16. #1992. 购票(ticket)
  17. 感染 <SCRIPT Language=VBScript> DropFileName = “svchost.exe” Ramnit 蠕虫病毒 HTML清除工具
  18. NVIDIA Control Panel 出现问题。请与你的系统管理员联系,以了解有关修复或重新安装该应用的信息。 关于win10安装新版N卡驱动没有显卡控制面板的解决办法
  19. 计算机组成原理基本概念
  20. 开源的RSS订阅器FreshRSS

热门文章

  1. 通过例子学TLA+(二) -- DieHard
  2. 论文快读:DETReg(CVPR2022)
  3. react-ssr之node代理
  4. 电脑不小心删除的文件怎么恢复?
  5. 2021FME博客大赛 —— 杭州城市西湖区活力评价
  6. 英文心灵鸡汤小记-2
  7. 我训练了一个AI来复制我的声音,结果吓坏了我
  8. Windows下Rstudio的下载安装步骤详解
  9. 如何升级vmware workstation虚拟机软件
  10. 数据科学与大数据分析之项目6-CNN模型图像分类