redis和mongodb工具类
2015-09-02 18:11
549 查看
import java.io.File;
import java.io.InputStream;
import com.mongodb.gridfs.GridFSDBFile;
/**
* Mongodb存取文件
*
*/
public interface FileDao {
/**
* 存储文件
* @param collectionName 集合名
* @param input 文件
* @param id 文件id
* @param aliases 别名
* @param filename 文件名称
* @throws Exception
*/
public void saveFile(String collectionName, File input, String id, String aliases, String filename) throws Exception;
/**
* 存储文件
* @param collectionName 集合名
* @param input 文件流
* @param id 文件id
* @param aliases 别名
* @param filename 文件名称
*/
public void saveFile(String collectionName, InputStream input, String id, String aliases, String filename);
/**
* 存储文件
* @param collectionName 集合名
* @param input 文件字节数组
* @param id 文件id
* @param aliases 别名
* @param filename 文件名称
*/
public void saveFile(String collectionName, byte[] input, String id, String aliases, String filename);
/**
* 获得一个文件
* @param collectionName 集合名
* @param id 文件id 可为空
* @param filename 文件名 可为空
* @return
*/
public GridFSDBFile retrieveFileOne(String collectionName, String id, String filename);
/**
* 获得一个文件
* @param collectionName 集合名
* @param id 文件名id
* @return
*/
public GridFSDBFile getFileById(String collectionName,String id);
/**
* 获得一个文件
* @param collectionName 集合名
* @param filename 文件名
* @return
*/
public GridFSDBFile getFileByFilename(String collectionName,String filename);
/**
* 删除文件
* @param collectionName 集合名
* @param id 文件名id
*/
public void delectFileById(String collectionName,String id);
/**
* 删除文件
* @param collectionName 集合名
* @param filename 文件名
*/
public void delectFileByFilename(String collectionName,String filename);
}
import java.io.InputStream;
import com.mongodb.gridfs.GridFSDBFile;
/**
* Mongodb存取文件
*
*/
public interface FileDao {
/**
* 存储文件
* @param collectionName 集合名
* @param input 文件
* @param id 文件id
* @param aliases 别名
* @param filename 文件名称
* @throws Exception
*/
public void saveFile(String collectionName, File input, String id, String aliases, String filename) throws Exception;
/**
* 存储文件
* @param collectionName 集合名
* @param input 文件流
* @param id 文件id
* @param aliases 别名
* @param filename 文件名称
*/
public void saveFile(String collectionName, InputStream input, String id, String aliases, String filename);
/**
* 存储文件
* @param collectionName 集合名
* @param input 文件字节数组
* @param id 文件id
* @param aliases 别名
* @param filename 文件名称
*/
public void saveFile(String collectionName, byte[] input, String id, String aliases, String filename);
/**
* 获得一个文件
* @param collectionName 集合名
* @param id 文件id 可为空
* @param filename 文件名 可为空
* @return
*/
public GridFSDBFile retrieveFileOne(String collectionName, String id, String filename);
/**
* 获得一个文件
* @param collectionName 集合名
* @param id 文件名id
* @return
*/
public GridFSDBFile getFileById(String collectionName,String id);
/**
* 获得一个文件
* @param collectionName 集合名
* @param filename 文件名
* @return
*/
public GridFSDBFile getFileByFilename(String collectionName,String filename);
/**
* 删除文件
* @param collectionName 集合名
* @param id 文件名id
*/
public void delectFileById(String collectionName,String id);
/**
* 删除文件
* @param collectionName 集合名
* @param filename 文件名
*/
public void delectFileByFilename(String collectionName,String filename);
}
import java.io.File; import java.io.InputStream; import javax.annotation.Resource; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Repository; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; import com.trustsaving.CacheMoudle.dao.FileDao; @Repository public class FileDaoImpl implements FileDao{ @Resource protected MongoTemplate mongoTemplate; @Override public void saveFile(String collectionName, File input, String id, String aliases, String filename) throws Exception{ if (collectionName==null||collectionName.trim().isEmpty()||input==null) { return; } if (!input.exists()||input.isDirectory()) { return; } delectFileById(collectionName,id); GridFS gfs =new GridFS(mongoTemplate.getDb(), collectionName); GridFSInputFile gfsFile = gfs.createFile(input); gfsFile.setId(id); if (filename!=null&&!filename.trim().isEmpty()) { gfsFile.setFilename(filename); gfsFile.setContentType(filename.substring(filename.lastIndexOf("."))); } if (aliases!=null&&!aliases.trim().isEmpty()) { gfsFile.put("aliases", aliases); } gfsFile.save(); } @Override public void saveFile(String collectionName, InputStream input, String id, String aliases, String filename) { if (collectionName==null||collectionName.trim().isEmpty()||input==null) { return; } delectFileById(collectionName,id); GridFS gfs =new GridFS(mongoTemplate.getDb(), collectionName); GridFSInputFile gfsFile = gfs.createFile(input); gfsFile.setId(id); if (filename!=null&&!filename.trim().isEmpty()) { gfsFile.setFilename(filename); gfsFile.setContentType(filename.substring(filename.lastIndexOf("."))); } if (aliases!=null&&!aliases.trim().isEmpty()) { gfsFile.put("aliases", aliases); } gfsFile.save(); } @Override public void saveFile(String collectionName, byte[] input, String id, String aliases, String filename) { if (collectionName==null||collectionName.trim().isEmpty()||input==null) { return; } delectFileById(collectionName,id); GridFS gfs =new GridFS(mongoTemplate.getDb(), collectionName); GridFSInputFile gfsFile = gfs.createFile(input); gfsFile.setId(id); if (filename!=null&&!filename.trim().isEmpty()) { gfsFile.setFilename(filename); gfsFile.setContentType(filename.substring(filename.lastIndexOf("."))); } if (aliases!=null&&!aliases.trim().isEmpty()) { gfsFile.put("aliases", aliases); } gfsFile.save(); } @Override public GridFSDBFile retrieveFileOne(String collectionName, String id, String filename) { if (collectionName==null||collectionName.trim().isEmpty()||(id==null&&filename==null)) { return null; } if (id!=null&&!id.trim().isEmpty()) { return getFileById(collectionName,id); } if (filename!=null&&!filename.trim().isEmpty()) { return getFileByFilename(collectionName,filename); } return null; } @Override public GridFSDBFile getFileById(String collectionName, String id) { if (collectionName==null||collectionName.trim().isEmpty()||id==null||id.trim().isEmpty()) { return null; } GridFS gfs =new GridFS(mongoTemplate.getDb(), collectionName); DBObject query = new BasicDBObject("_id", id); GridFSDBFile gfsFile = gfs.findOne(query); return gfsFile; } @Override public GridFSDBFile getFileByFilename(String collectionName, String filename) { if (collectionName==null||collectionName.trim().isEmpty()||filename==null||filename.trim().isEmpty()) { return null; } GridFS gfs =new GridFS(mongoTemplate.getDb(), collectionName); GridFSDBFile gfsFile = gfs.findOne(filename); return gfsFile; } @Override public void delectFileById(String collectionName, String id) { if (collectionName==null||collectionName.trim().isEmpty()||id==null||id.trim().isEmpty()) { return; } GridFS gfs =new GridFS(mongoTemplate.getDb(), collectionName); DBObject query = new BasicDBObject("_id", id); gfs.remove(query); } @Override public void delectFileByFilename(String collectionName, String filename) { if (collectionName==null||collectionName.trim().isEmpty()||filename==null||filename.trim().isEmpty()) { return; } GridFS gfs =new GridFS(mongoTemplate.getDb(), collectionName); gfs.remove(filename); } }
import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** * 缓存redis类 * */ public interface CacheRedis { /** * 保存对象 * @param key 键 * @param object 对象 * @param timeout 过期时间 * @param unit 时间单位 */ public void setObject(String key,Object object,final long timeout, final TimeUnit unit); /** * 保存对象 * @param key 键 * @param map 对象map * @param timeout 过期时间 * @param unit 时间单位 */ public void setObject(String key,Map<String, Object> map,final long timeout, final TimeUnit unit); /** * 保存对象 * @param key 键 * @param list 对象list * @param timeout 过期时间 * @param unit 时间单位 */ public void setObject(String key,List<Object> list,final long timeout, final TimeUnit unit); /** * 保存对象 * @param key 键 * @param set 对象set * @param timeout 过期时间 * @param unit 时间单位 */ public void setObject(String key,Set<Object> set,final long timeout, final TimeUnit unit); /** * 保存对象 * @param key 键 * @param object 对象 */ public void setObject(String key,Object object); /** * 保存对象 * @param key 键 * @param map 对象map */ public void setObject(String key,Map<String, Object> map); /** * 保存对象 * @param key 键 * @param list 对象list */ public void setObject(String key,List<Object> list); /** * 保存对象 * @param key 键 * @param set 对象set */ public void setObject(String key,Set<Object> set); /** * 获取对象 * @param key 键 * @return 对象 */ public Object getObject(String key); /** * * @param key 键 * @return 对象map */ public Map<String, Object> getObjectMap(String key); /** * * @param key 键 * @return 对象list */ public List<Object> getObjectList(String key); /** * * @param key 键 * @return 对象set */ public Set<Object> getObjectSet(String key); /** * 获取hash中对象 * @param key 键 * @param hashKey hash键 * @return 对象 */ public Object getObject(String key,String hashKey); /** * 增加list的对象 * @param key 键 * @param listKey list键 * @param object 对象 */ public void addListObject(String key,Object object); /** * 增加set的对象 * @param key 键 * @param setKey set键 * @param object 对象 */ public void addSetObject(String key,Object object); }
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import org.springframework.data.redis.core.BoundHashOperations; import org.springframework.data.redis.core.BoundListOperations; import org.springframework.data.redis.core.BoundSetOperations; import org.springframework.stereotype.Repository; import com.trustsaving.CacheMoudle.redis.CacheRedis; import com.trustsaving.common.base.dao.AbstractBaseRedisDao; @Repository public class CacheRedisImpl extends AbstractBaseRedisDao<String, Object> implements CacheRedis{ @Override public void setObject(String key, Object object, long timeout, TimeUnit unit) { if (key==null||object==null) { return; } setObject(key, object); redisTemplate.expire(key, timeout, unit); } @Override public void setObject(String key, Map<String, Object> map, long timeout, TimeUnit unit) { if (key==null||map==null) { return; } setObject(key, map); redisTemplate.expire(key, timeout, unit); } @Override public void setObject(String key, List<Object> list, long timeout, TimeUnit unit) { if (key==null||list==null) { return; } setObject(key, list); redisTemplate.expire(key, timeout, unit); } @Override public void setObject(String key, Set<Object> set, long timeout, TimeUnit unit) { if (key==null||set==null) { return; } setObject(key, set); redisTemplate.expire(key, timeout, unit); } @Override public void setObject(String key, Object object) { if (key==null||object==null) { return; } redisTemplate.opsForValue().set(key, object); } @Override public void setObject(String key, Map<String, Object> map) { if (key==null||map==null||map.size()<=0) { return; } redisTemplate.opsForHash().putAll(key, map); } @Override public void setObject(String key, List<Object> list) { if (key==null||list==null||list.size()<=0) { return; } redisTemplate.opsForList().leftPushAll(key, list); } @Override public void setObject(String key, Set<Object> set) { if (key==null||set==null||set.size()<=0) { return; } for (Object object : set) { redisTemplate.opsForSet().add(key, object); } } @Override public Object getObject(String key) { if (key==null||key.trim().isEmpty()) { return null; } return redisTemplate.opsForValue().get(key); } @Override public Map<String, Object> getObjectMap(String key) { if (key==null||key.trim().isEmpty()) { return null; } BoundHashOperations<String, String, Object> bho= redisTemplate.boundHashOps(key); Set<String> keySet= bho.keys(); if (keySet==null||keySet.size()<=0) { return null; } Map<String, Object> map=new HashMap<String,Object>(); for (String string : keySet) { map.put(string, bho.get(string)); } return map; } @Override public List<Object> getObjectList(String key) { if (key==null||key.trim().isEmpty()) { return null; } BoundListOperations<String, Object> blo=redisTemplate.boundListOps(key); return blo.range(0, -1); // Long size= blo.size(); // if (size==null||size<=0) { // return null; // } // List<Object> list=new ArrayList<Object>(); // for (int i = 0; i < size; i++) { // list.add(blo.index(i)); // } // return list; } @Override public Set<Object> getObjectSet(String key) { if (key==null||key.trim().isEmpty()) { return null; } BoundSetOperations<String, Object> bso=redisTemplate.boundSetOps(key); return bso.members(); } @Override public Object getObject(String key, String hashKey) { if (key==null||key.trim().isEmpty()||hashKey==null||hashKey.trim().isEmpty()) { return null; } BoundHashOperations<String, String, Object> bho=redisTemplate.boundHashOps(key); return bho.get(hashKey); } @Override public void addListObject(String key, Object object) { if (key==null||key.trim().isEmpty()||object==null) { return ; } redisTemplate.opsForList().leftPush(key, object); } @Override public void addSetObject(String key, Object object) { if (key==null||key.trim().isEmpty()||object==null) { return ; } redisTemplate.opsForSet().add(key, object); } }
import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; /** * 缓存redis工具类 * */ public interface CacheUtilRedis { /** * 删除键 * @param key 键 */ public void delete(String key); /** * 删除键 * @param list 键列表 */ public void delete(List<String> list); /** * 删除hash中键 * @param key 键 * @param hashKey hash键 */ public void delete(String key,String hashKey); /** * 删除set中值 * @param key 键 * @param object set值 */ public void remove(String key,Object object); /** * 判断是否为set的成员 * @param key 键 * @param object set值 * @return */ public Boolean isMember(String key,Object object); /** * 是否存在键 * @param key 键 * @return true存在 */ public Boolean hasKey(String key); /** * hash中是否存在键 * @param key 键 * @param hashKey hash键 * @return true存在 */ public Boolean hasKey(String key,String hashKey); /** * 设置键过期时间 * @param key 键 * @param timeout 过期时间 * @param unit 时间单位 * @return true设置成功 */ public Boolean expire(String key, final long timeout, final TimeUnit unit); /** * 设置键过期时间 * @param key * @param date 失效日期 * @return true设置成功 */ public Boolean expireAt(String key, final Date date); /** * 获得键过期时间 * @param key 键 * @param unit 时间单位 * @return 过期时间 */ public Long getExpire(String key, final TimeUnit unit); }
import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import org.springframework.stereotype.Repository; import com.trustsaving.CacheMoudle.redis.CacheUtilRedis; import com.trustsaving.common.base.dao.AbstractBaseRedisDao; @Repository public class CacheUtilRedisImpl extends AbstractBaseRedisDao<String, Object> implements CacheUtilRedis{ @Override public void delete(String key) { if (key==null||key.trim().isEmpty()) { return; } redisTemplate.delete(key); } @Override public void delete(List<String> list) { if (list==null||list.size()<=0) { return; } redisTemplate.delete(list); } @Override public void delete(String key, String hashKey) { if (key==null||key.trim().isEmpty()||hashKey==null||hashKey.trim().isEmpty()) { return; } redisTemplate.opsForHash().delete(key, hashKey); } @Override public void remove(String key, Object object) { if (key==null||key.trim().isEmpty()||object==null) { return; } redisTemplate.opsForSet().remove(key, object); } @Override public Boolean isMember(String key, Object object) { if (key==null||key.trim().isEmpty()||object==null) { return false; } return redisTemplate.opsForSet().isMember(key, object); } @Override public Boolean hasKey(String key) { if (key==null||key.trim().isEmpty()) { return false; } return redisTemplate.hasKey(key); } @Override public Boolean hasKey(String key, String hashKey) { if (key==null||key.trim().isEmpty()||hashKey==null||hashKey.trim().isEmpty()) { return false; } return redisTemplate.opsForHash().hasKey(key, hashKey); } @Override public Boolean expire(String key, long timeout, TimeUnit unit) { if (key==null||key.trim().isEmpty()||unit==null) { return false; } return redisTemplate.expire(key, timeout, unit); } @Override public Boolean expireAt(String key, Date date) { if (key==null||key.trim().isEmpty()||date==null) { return false; } return redisTemplate.expireAt(key, date); } @Override public Long getExpire(String key, TimeUnit unit) { if (key==null||key.trim().isEmpty()||unit==null) { return null; } return redisTemplate.getExpire(key, unit); } }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.URL; import com.trustsaving.CacheMoudle.exception.SerializeException; /** * 对象序列化类 * */ public class SerializeUtil { /** * 序列化对象 * @param object * @return */ public static byte[]serialize(Object object) throws SerializeException,Exception{ if (object==null) { throw new SerializeException(SerializeException.PARAM_IS_NULL, "序列化参数为空"); } 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) { throw e; } } /** * 反序列化对象 * @param bytes * @return */ public static Object unserialize(byte[]bytes)throws SerializeException,Exception{ if (bytes==null) { throw new SerializeException(SerializeException.PARAM_IS_NULL, "反序列化参数为空"); } ByteArrayInputStream bais = null; try { bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { throw e; } } /** * 文件序列化 * @param input 文件地址 * @return */ public static byte[] serializeFile(String input)throws SerializeException,Exception{ if (input==null) { throw new SerializeException(SerializeException.PARAM_IS_NULL, "序列化参数为空"); } File fr = new File(input); if (fr==null||fr.exists()==false||fr.isDirectory()) { throw new SerializeException(SerializeException.IS_NOT_FILE, "文件不存在或是目录"); } try { FileInputStream fis=new FileInputStream(fr); return readInputStream(fis); } catch (Exception e) { throw e; } } /** * 文件序列化 * @param input 文件 * @return */ public static byte[] serializeFile(File input)throws SerializeException,Exception{ if (input==null) { throw new SerializeException(SerializeException.PARAM_IS_NULL, "序列化参数为空"); } if (input.exists()==false||input.isDirectory()) { throw new SerializeException(SerializeException.IS_NOT_FILE, "文件不存在或是目录"); } try { FileInputStream fis=new FileInputStream(input); return readInputStream(fis); } catch (Exception e) { throw e; } } /** * 文件序列化 * @param input 文件流 * @return */ public static byte[] serializeFile(InputStream input)throws SerializeException,Exception{ if (input==null) { throw new SerializeException(SerializeException.PARAM_IS_NULL, "序列化参数为空"); } try { return readInputStream(input); } catch (Exception e) { throw e; } } /** * 文件序列化 * @param input URL对象 * @return */ public static byte[] serializeFile(URL input)throws SerializeException,Exception{ if (input==null) { throw new SerializeException(SerializeException.PARAM_IS_NULL, "序列化参数为空"); } InputStream istream = null; try { istream = input.openStream(); return readInputStream(istream); } catch (IOException e) { throw e; } } /** * 文件反序列化 * @param bytes 文件流 * @return */ public static InputStream unserializeFile(byte[]bytes)throws SerializeException,Exception{ if (bytes==null) { throw new SerializeException(SerializeException.PARAM_IS_NULL, "反序列化参数为空"); } InputStream inputStream=new ByteArrayInputStream(bytes); return inputStream; } // /** // * 从网络序列化图片 // * @param imageUrl // * @return // */ // public static byte[] serializeImage(URL imageUrl )throws SerializeException,Exception{ // String[] imageFormats = ImageIO.getReaderFormatNames(); // for (String string : imageFormats) { // System.out.println(string); // } // ByteArrayOutputStream outputStream = null; // try { // BufferedImage bufferedImage = ImageIO.read(imageUrl); // outputStream = new ByteArrayOutputStream(); // ImageIO.write(bufferedImage, "jpg", outputStream); // } catch (IOException e) { // e.printStackTrace(); // } // return outputStream.toByteArray(); // } /** * 读取文件为byte数组 * @param inStream * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); //创建一个Buffer字符串 byte[] buffer = new byte[1024]; //每次读取的字符串长度,如果为-1,代表全部读取完毕 int len = 0; //使用一个输入流从buffer里把数据读取出来 while( (len=inStream.read(buffer)) != -1 ){ //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 outStream.write(buffer, 0, len); } //关闭输入流 inStream.close(); //把outStream里的数据写入内存 return outStream.toByteArray(); } }
相关文章推荐
- [Redis]通过代码配置Redis
- [Redis]如何通过Powershell创建Redis服务
- 深入剖析 redis 事件驱动
- Redis+Keepalived内存数据库集群配置
- Redis+Keepalived内存数据库集群配置
- 从hiredis使用出core谈谈redis多线程的使用【转】
- Redis bind用法
- Redis学习总结(JAVA篇)
- redis简单消息队列
- 超强、超详细Redis数据库入门教程
- redis查看中文
- go-redis in golang
- redis五种数据类型应用场景
- Kafka+Spark Streaming+Redis实时计算整合实践
- CentOS7安装配置redis-3.0.0
- redis使用注意问题
- redis 如何处理客户端连接
- Codis作者黄东旭细说分布式Redis架构设计和踩过的那些坑们
- Redis windows学习(二)——Redis的AOF模式和RDB模式
- 关于Spring Data redis几种对象序列化的比较