Redis:存储对象的两种方式(序列化和json字符串)
方式一:序列化操作
- public class SerializeUtil {
- /*
- * 序列化
- * */
- public static byte[] serizlize(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) {
- e.printStackTrace();
- }finally {
- try {
- if(baos != null){
- baos.close();
- }
- if (oos != null) {
- oos.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return null;
- }
- /*
- * 反序列化
- * */
- public static Object deserialize(byte[] bytes){
- ByteArrayInputStream bais = null;
- ObjectInputStream ois = null;
- try{
- bais = new ByteArrayInputStream(bytes);
- ois = new ObjectInputStream(bais);
- return ois.readObject();
- }catch(Exception e){
- e.printStackTrace();
- }finally {
- try {
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return null;
- }
- }
获取jedis实例
- public class RedisConnection {
- private static String HOST = "127.0.0.1";
- private static int PORT = 6379;
- private static int MAX_ACTIVE = 1024;
- private static int MAX_IDLE = 200;
- private static int MAX_WAIT = 10000;
- private static JedisPool jedisPool = null;
- /*
- * 初始化redis连接池
- * */
- private static void initPool(){
- try {
- JedisPoolConfig config = new JedisPoolConfig();
- config.setMaxTotal(MAX_ACTIVE);//最大连接数
- config.setMaxIdle(MAX_IDLE);//最大空闲连接数
- config.setMaxWaitMillis(MAX_WAIT);//获取可用连接的最大等待时间
- jedisPool = new JedisPool(config, HOST, PORT);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /*
- * 获取jedis实例
- * */
- public synchronized static Jedis getJedis() {
- try {
- if(jedisPool == null){
- initPool();
- }
- Jedis jedis = jedisPool.getResource();
- jedis.auth("redis");//密码
- return jedis;
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- }
redis操作
- public class RedisOps {
- public static void set(String key,String value){
- Jedis jedis = RedisConnection.getJedis();
- jedis.set(key, value);
- jedis.close();
- }
- public static String get(String key){
- Jedis jedis = RedisConnection.getJedis();
- String value = jedis.get(key);
- jedis.close();
- return value;
- }
- public static void setObject(String key,Object object){
- Jedis jedis = RedisConnection.getJedis();
- jedis.set(key.getBytes(), SerializeUtil.serizlize(object));
- jedis.close();
- }
- public static Object getObject(String key){
- Jedis jedis = RedisConnection.getJedis();
- byte[] bytes = jedis.get(key.getBytes());
- jedis.close();
- return SerializeUtil.deserialize(bytes);
- }
- }
实体类
- public class User implements Serializable{
- private static final long serialVersionUID = -3210884885630038713L;
- private int id;
- private String name;
- public User(){
- }
- public User(int id,String name){
- this.id = id;
- this.name = name;
- }
- //setter和getter方法
- }
测试用例
- public class RedisTest {
- @Test
- public void testString(){
- RedisOps.set("user:1", "sisu");
- String user = RedisOps.get("user:1");
- Assert.assertEquals("sisu", user);
- }
- @Test
- public void testObject(){
- RedisOps.setObject("user:2",new User(2,"lumia"));
- User user = (User)RedisOps.getObject("user:2");
- Assert.assertEquals("lumia", user.getName());
- }
- }
方式二:使用fastjson将对象转为json字符串后存储
- public class RedisOps {
- public static void setJsonString(String key,Object object){
- Jedis jedis = RedisConnection.getJedis();
- jedis.set(key, JSON.toJSONString(object));
- jedis.close();
- }
- public static Object getJsonObject(String key,Class clazz){
- Jedis jedis = RedisConnection.getJedis();
- String value = jedis.get(key);
- jedis.close();
- return JSON.parseObject(value,clazz);
- }
- }
测试:
- @Test
- public void testObject2(){
- RedisOps.setJsonString("user:3", new User(3,"xiaoming"));
- User user = (User)RedisOps.getJsonObject("user:3",User.class);
- Assert.assertEquals("xiaoming", user.getName());
Redis:存储对象的两种方式(序列化和json字符串)的更多相关文章
- Redis 备份数据的两种方式
既然是数据库,那就一定有数据备份方式了,而且 Redis 是内存形式的数据库,更需要数据备份了,要不然断电数据就全都丢失了. Redis 数据备份有两种方式: RDB(数据快照) AOF(记录操作日志 ...
- iOS:创建单例对象的两种方式
单例模式:创建单例对象的两种方式 方式一:iOS4版本之前 static SingleClassManager *singleManager = nil; +(SingleClas ...
- Python与数据库[2] -> 关系对象映射/ORM[2] -> 建立声明层表对象的两种方式
建立声明层表对象的两种方式 在对表对象进行建立的时候,通常有两种方式可以完成,以下是两种方式的建立过程对比 首先导入需要的模块,获取一个声明层 from sqlalchemy.sql.schema i ...
- Java反射02 : Class对象获取的三种方式和通过反射实例化对象的两种方式
1.Class对象获取的三种方式 本文转载自:https://blog.csdn.net/hanchao5272/article/details/79361463 上一章节已经说过,一般情况下,Jav ...
- Redis数据持久化的两种方式RDB和AOF
由于Redis的数据都存放在内存中,如果没有配置持久化,redis重启后数据就全丢失了,于是需要开启redis的持久化功能,将数据保存到磁 盘上,当redis重启后,可以从磁盘中恢复数据.redis提 ...
- Asp.net Web API 返回Json对象的两种方式
这两种方式都是以HttpResponseMessage的形式返回, 方式一:以字符串的形式 var content = new StringContent("{\"FileName ...
- Redis的持久化的两种方式drbd以及aof日志方式
redis的持久化配置: 主要包括两种方式:1.快照 2 日志 来看一下redis的rdb的配置选项和它的工作原理: save 900 1 // 表示的是900s内,有1条写入,则产生快照 save ...
- JS中访问对象的两种方式区别
可以使用下面两种方式访问对象的属性和方法 1.对象名.属性名 对象名.方法名() 2.对象名["属性名"] 对象名["方法名"]() var obj = { n ...
- hibernate载入持久化对象的两种方式——get、load
一.get与load对照 在hibernate中get和load方法是依据id取得持久化对象的两种方法.但在实际使用的过程中总会把两者混淆,不知道什么情况下使用get好,什么时候使用load方法效率更 ...
随机推荐
- 算法Sedgewick第四版-第1章基础-2.1Elementary Sortss-008排序算法的复杂度(比较次数的上下限)
一. 1. 2.
- clions的使用
最近无聊玩了下CLion这个IDE,顺便学习了下CMAKE怎么使用.话说CLion的CMAKE的支持还不是特别的完好,和命令行模式还有有区别,有如下几个问题: 1:CMAKE的编译目录不能指定,而是I ...
- cs231n knn
# coding: utf-8 # In[19]: import random import numpy as np from cs231n.data_utils import load_CIFAR1 ...
- [译]在Javascript中进行日期相关的操作
本文翻译youtube上的up主kudvenkat的javascript tutorial播放单 源地址在此: https://www.youtube.com/watch?v=PMsVM7rjupU& ...
- SPOJ - BALNUM Balanced Numbers(数位dp+三进制状压)
Balanced Numbers Balanced numbers have been used by mathematicians for centuries. A positive integer ...
- access + vb + asp 遇到一些问题的总结
Data Base access + vb + asp 遇到一些问题的总结 1.asp中sql语句: select * from users whre name=’张三‘ and addTime=# ...
- ubuntu - 14.04,创建菜单
我们有的时候可能会把一个执行程序放到一个位置,随后我们希望在ubuntu的菜单里面加入它,这个操作非常简单: 我在Gnome桌面里,选择:“系统工具”->“首选项”->"主菜单& ...
- B - Factors of Factorial
Problem Statement You are given an integer N. Find the number of the positive divisors of N!, modulo ...
- [haut] 1281: 邪能炸弹 dp
题目描述 正在入侵艾泽拉斯的古尔丹偶然间得到了一颗邪能炸弹,经过研究,他发现这是一颗威力极其巨大且难以控制的炸弹.但是精通邪能的古尔丹突然有了一个大胆的想法,他对炸弹进行了一些小小的改造.这使得炸弹需 ...
- #学习笔记# VALSE 2019.01.09 朱俊彦 --- Learning to Synthesize Images, Videos, and 3D Objects
视频类型:VALSE-webinar 报告时间:2019年01月09日 报告人:MIT朱俊彦 报告题目:Learning to Synthesize Images, Videos, and 3D Ob ...