package com.jsh.dao.cache;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import com.jsh.model.po.Material;
import com.opensymphony.xwork2.util.logging.Logger;
import com.opensymphony.xwork2.util.logging.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
* @author guoli
* @Time 2019年2月28日 下午2:41:38
* @Description:TODO
* @version 1.0
*/
public class RedisDao {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final JedisPool jedisPool;
private RuntimeSchema<Material> schema = RuntimeSchema.createFrom(Material.class);
public RedisDao(String ip, int port) {
jedisPool = new JedisPool(ip, port);
}
public Material getMaterial(long materialId) {
// redis 操作逻辑
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "material:" + materialId;
// 并没有实现内部的序列化操作
// get-byte[]-反序列化-object
// 采用自定义序列化protostuff
byte[] bytes = jedis.get(key.getBytes());
if (bytes != null) {
// 空对象
Material material = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes, material, schema);// 作用material
// 反序列化,更节省空间
return material;
}
} finally {
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
public String putMaterial(Material material) {
// set object-->序列化---> bytep[]
try {
Jedis jedis = jedisPool.getResource();
try {
String key = "material:" + material.getId();
byte[] bytes = ProtostuffIOUtil.toByteArray(material, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
// 超时缓存
int timeout = 60 * 60;// 一个小时
return jedis.setex(key.getBytes(), timeout, bytes);
} finally {
jedis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
}
业务层代码
public void exportMaterial(long id){
//优化缓存
// 1.访问redis
Material material=redisDao.getMaterial(id);
if(material==null){
//访问数据库
material=materialService.get(model.getMaterialID());
if(material!=null){
//存入redis
redisDao.putMaterial(material);
}
}
}
redis和protostuff
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.3</version>
</dependency>
<!-- 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>