Redis如何存储对象与集合示例详解
前言
大家都知道在项目中,缓存以及mq消息队列可以说是不可或缺的2个重要技术。前者主要是为了减轻数据库压力,大幅度提升性能。后者主要是为了提高用户的体验度,我理解的是再后端做的一个ajax请求(异步),并且像ribbmitmq等消息队列有重试机制等功能。
这里主要讲redis/303688.html">redis如何把对象,集合存入,并且取出。下面话不多说了,来一起看看详细的介绍吧。
1.在启动类上加入如下代码
private Jedis jedis;private JedisPoolConfig config;private JedisShardInfo sharInfo;@Beanpublic Jedis jedis(){//连接redis服务器,192.168.0.100:6379// jedis = new Jedis("192.168.0.100", 6379);// //权限认证// jedis.auth("123456");// 操作单独的文本串config = new JedisPoolConfig();
config.setMaxIdle(1000);//最大空闲时间config.setMaxWaitMillis(1000); //最大等待时间config.setMaxTotal(500); //redis池中最大对象个数sharInfo = new JedisShardInfo("192.168.0.100", 6379);
sharInfo.setPassword("123456");
sharInfo.setConnectionTimeout(5000);//链接超时时间jedis = new Jedis(sharInfo);return jedis;
}
2.在application.yml当中加入redis配置
spring:
redis:
database: 0
host: 101.132.191.77
port: 6379
password: 123456
pool:
max-idle: 8 #连接池最大连接数(使用负值表示没有限制)
min-idle: 0 # 连接池中的最小空闲连接
max-active: 8 # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1 # 连接池中的最大空闲连接
timeout: 5000 # 连接超时时间(毫秒)
3.新建SerializeUtil类,这个类主要是为了将对象序列化redis当中
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;/**
public class SerializeUtil
{
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 (Exception e) { }return null;
}
public static Object unserialize( byte[] bytes) {
ByteArrayInputStream bais = null;
try {
// 反序列化bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) { }return null;
}
}
4.我封装了一个RedisServiceImpl类,主要是用对redis设值和取值
import com.ys.util.redis.SerializeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class RedisServiceImpl {@Autowired private StringRedisTemplate stringRedisTemplate;
@Autowired
private Jedis jedis;
public void setStr(String key, String value) {
setStr(key, value, null);
}
public void setStr(String key, Object value, Long time)
{if(value == null){
return;
}if(value instanceof String){
String obj = (String) value;
stringRedisTemplate.opsForValue().set(key, obj);
}else if(value instanceof List){
List obj = (List) value;
stringRedisTemplate.opsForList().leftPushAll(key,obj);
}else if(value instanceof Map){
Map obj = (Map) value;
stringRedisTemplate.opsForHash().putAll(key,obj);
}if (time != null)
stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
}
public Object getKey(String key)
{return stringRedisTemplate.opsForValue().get(key);
}
public void delKey(String key) {
stringRedisTemplate.delete(key);
}
public boolean del(String key)
{return jedis.del(key.getBytes())>0;
}
}
5.测试redis是否ok,编写redisController类
import com.ys.service.impl.RedisServiceImpl;
import com.ys.vo.IqProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController public class RedisServiceController {
@Autowired private RedisServiceImpl redisService;
@RequestMapping(value = "/setredis")
public String setredis(String keyredis){
redisService.setStr(keyredis,"2018年1月26日");
return "保存成功,请访问getredis查询redis";
}
@RequestMapping(value = "/setObj")
public String setObj(String keyredis){
IqProduct iqProduct = new IqProduct();
iqProduct.setSort(1);
iqProduct.setTimestamp(new Date().getTime());
iqProduct.setProductName("productname");
// list.add(iqProduct);
redisService.set(keyredis, iqProduct);
return "保存成功,请访问getredis查询redis";
}
@RequestMapping(value = "/getObj")
public Object getObj(String keyredis){
Object object = redisService.get(keyredis);
if(object !=null){
IqProduct iqProduct = (IqProduct) object;
System. out.println(iqProduct.getProductName());
System. out.println(iqProduct.getId());
System. out.println(iqProduct.getTimestamp());
}return object;
}
@RequestMapping(value = "/delObj")
public boolean delObj(String keyredis)
{boolean del = redisService.del(keyredis);
return del;
}
@RequestMapping(value = "/getredis")
public String getredis(String keyredis){
String getredis = (String) redisService.getKey(keyredis);
return "redis的key是===>"+getredis;
}
@RequestMapping(value = "/delredis")
public String delredis(String keyredis){
redisService.delKey(keyredis);
return "删除成功,请通过getredis进行查询";
}
@RequestMapping(value = "/setList")
public String setList(String keyredis){
List list = new ArrayList();for (int i = 0;i<10;i++){
IqProduct iqProduct = new IqProduct();
iqProduct.setSort(1);
iqProduct.setTimestamp(new Date().getTime());
iqProduct.setProductName("productname");
list.add(iqProduct);
}
redisService.set(keyredis, list);
return "保存成功,请访问getredis查询redis";
}
@RequestMapping(value = "/getList")
public Object getList(String keyredis){
Object object = redisService.get(keyredis);
if(object !=null){
List<IqProduct> iqProducts = (List<IqProduct>) object;
for (int i = 0;i<iqProducts.size();i++){
IqProduct iqProduct = iqProducts.get(i);
System. out.println(iqProduct.getProductName());
System. out.println(iqProduct.getId());
System. out.println(iqProduct.getTimestamp());
}
}return object;
}
@RequestMapping(value = "/delList")
public boolean delList(String keyredis)
{
boolean del = redisService.del(keyredis);return del;
}
}
6.测试结果

总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU源码库的支持。
Redis如何存储对象与集合示例详解的更多相关文章
- redis是如何存储对象和集合的
在项目中,缓存以及mq消息队列可以说是不可或缺的2个重要技术.前者主要是为了减轻数据库压力,大幅度提升性能.后者主要是为了提高用户的体验度,我理解的是再后端做的一个ajax请求(异步),并且像ribb ...
- asp.net中C#对象与方法 属性详解
C#对象与方法 一.相关概念: 1.对象:现实世界中的实体 2. 类:具有相似属性和方法的对象的集合 3.面向对象程序设计的特点:封装 继承 多态 二.类的定义与语法 1.定义类: 修饰符 类名称 ...
- java集合框架详解
java集合框架详解 一.Collection和Collections直接的区别 Collection是在java.util包下面的接口,是集合框架层次的父接口.常用的继承该接口的有list和set. ...
- Java集合中List,Set以及Map等集合体系详解
转载请注明出处:Java集合中List,Set以及Map等集合体系详解(史上最全) 概述: List , Set, Map都是接口,前两个继承至collection接口,Map为独立接口 Set下有H ...
- Python操作redis系列以 哈希(Hash)命令详解(四)
# -*- coding: utf-8 -*- import redis #这个redis不能用,请根据自己的需要修改 r =redis.Redis(host=") 1. Hset 命令用于 ...
- SpringBoot与PageHelper的整合示例详解
SpringBoot与PageHelper的整合示例详解 1.PageHelper简介 PageHelper官网地址: https://pagehelper.github.io/ 摘要: com.gi ...
- JavaScript对象的property属性详解
JavaScript对象的property属性详解:https://www.jb51.net/article/48594.htm JS原型与原型链终极详解_proto_.prototype及const ...
- 史上最易懂——ReactNative分组列表SectionList使用详情及示例详解
React Native系列 <逻辑性最强的React Native环境搭建与调试> <ReactNative开发工具有这一篇足矣> <解决React Native un ...
- Spring Boot 2.x 快速入门(下)HelloWorld示例详解
上篇 Spring Boot 2.x 快速入门(上)HelloWorld示例 进行了Sprint Boot的快速入门,以实际的示例代码来练手,总比光看书要强很多嘛,最好的就是边看.边写.边记.边展示. ...
随机推荐
- VC++ 6.0 C8051F340 USB PC侧通信 Demo
// HelloWorld.cpp : Defines the entry point for the console application. // /*********************** ...
- liunx中安装包及其应用
1. dpkg -i <package> 安装包 dpkg -r <package> 删除包 dpkg -P <package> 移除包和配置文件 dpkg ...
- HDU 2089:不要62
Problem Description 杭州人称那些傻乎乎粘嗒嗒的人为62(音:laoer). 杭州交通管理局经常会扩充一些的士车牌照,新近出来一个好消息,以后上牌照,不再含有不吉利的数字了,这样一来 ...
- hdu1224 dp(dp + 栈/父亲数组记录路径)
题意:给定 n 个城市的有趣度,并给出可以从那些城市飞到那些城市.其中第一个城市即起始城市同样也作为终点城市,有趣度为 0,旅行途中只允许按有趣度从低到高旅行,问旅行的有趣度最大是多少,并输出旅行路径 ...
- 【spring源码分析】面向切面编程架构设计
2 注解说明 2.1 @Aspect 作用是把当前类标识为一个切面供容器读取 2.2 @Before标识一个前置增强方法,相当于BeforeAdvice的功能,相似功能的还有 2.3 @AfterRe ...
- LeetCode Pascal's Triangle && Pascal's Triangle II Python
Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For example, given ...
- Dataframe 新增一列, apply 通用方法
df['c'] = df.apply(lambda row: 1 if row['a'] < 0 and row['b'] > 0 else 0, axis=1) apply 是一个好方法 ...
- 移动端 元素外面使用伪类after加边框 导致其内部元素无法选中
解决方法:给内部元素增加属性 position: relative; z-index: 3; 这样就能选中其内部元素了.
- MySQL删除超大表操作
======================================================================== 问题原因 通常情况下,会使用innodb_file_p ...
- ORACLE expdp/impdp详解
ORCALE10G提供了新的导入导出工具,数据泵.Oracle官方对此的形容是:Oracle DataPump technology enables Very High-Speed movement ...