Redis+protostuff简单实现对象及集合缓存

Maven中主要依赖:

 <dependencies>
        <!--protostuff序列化依赖-->
        <dependency>
            <groupId>com.dyuproject.protostuff</groupId>
            <artifactId>protostuff-core</artifactId>
            <version>1.0.8</version>
        </dependency>
        <dependency>
            <groupId>com.dyuproject.protostuff</groupId>
            <artifactId>protostuff-runtime</artifactId>
            <version>1.0.8</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.3</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

首先创建一个User的POJO

public class User {
    private String id;
    private String name;
    private int age;
    private boolean sex;

    public User(String id, String name, int age, boolean sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public User() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isSex() {
        return sex;
    }

    public void setSex(boolean sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", sex=" + sex +
                '}';
    }
}

接着封装Redis操作层,其中有四个方法,分别为存、取User对象和存、取User集合

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class RedisDao {
    private JedisPool jedisPool;

    public RedisDao(String ip, int port) {
        this.jedisPool = new JedisPool(ip, port);
    }

    //得到User的schema
    private RuntimeSchema<User> schema = RuntimeSchema.createFrom(User.class);

    //取User
    public User getUser(String id) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String key = "User" + id;
            byte[] bytes = jedis.get(key.getBytes());
            if (bytes != null) {
                User user = schema.newMessage();//空对象
                //byte[] -> 反序列化 -> Object(User)
                ProtostuffIOUtil.mergeFrom(bytes, user, schema);
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    //存User
    public String setUser(User user) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String key = "User" + user.getId();
            //Object(User) -> 序列化(byte[])
            byte[] bytes = ProtostuffIOUtil.toByteArray(user, schema,
                    LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
            int timeOut = 60 * 60;//超时缓存,一小时(单位是秒)
            String result = jedis.setex(key.getBytes(), timeOut, bytes);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    //取User集合
    public List<User> getUserList(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            byte[] bytes = jedis.get(key.getBytes());
            List<User> users = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(bytes), schema);
            return users;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }

    //存user集合
    public String setUserList(List<User> users, String key) {
        Jedis jedis = null;
        ByteArrayOutputStream bos = null;
        try {
            jedis = jedisPool.getResource();
            bos = new ByteArrayOutputStream();
            ProtostuffIOUtil.writeListTo(bos, users, schema,
                    LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
            int timeOut = 60 * 60;
            String result = jedis.setex(key.getBytes(), timeOut, bos.toByteArray());
            return result;
        } catch (Exception e) {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (jedis != null) {
                jedis.close();
            }
        }
        return null;
    }
}

最后编写测试类:

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class RedisDaoTest {

    RedisDao redisDao = new RedisDao("localhost", 6379);

    @Test
    public void setAndGetUser() throws Exception {
        String uId = "123456";
        //Redis存数据成功会返回OK字符串
        String result = redisDao.setUser(new User(uId, "小明", 15, true));
        System.out.println(result);
        User user = redisDao.getUser(uId);
        System.out.println(user);
    }

    @Test
    public void setAndGetUserList() throws Exception {
        String key = "UserList";
        List<User> users = new ArrayList<User>();
        users.add(new User("456789", "Jeck", 25, true));
        users.add(new User("123789", "Rose", 22, false));
        users.add(new User("741852", "Lili", 19, false));
        String result = redisDao.setUserList(users, key);
        System.out.println(result);
        users = redisDao.getUserList(key);
        System.out.println(users);
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值