redis 如何 把文件对象存进去

最近学习下redis,作为一个高性能的k/v数据库,如果数据不用swap的话,redis的性能是无以伦比的。
最近在做一个系统附件的缓存,试着把附件放到redis试试,写了个保存文件的方法。
public class TestRedis
{
Jedis redis = new Jedis("localhost");
//序列化方法
public byte[] object2Bytes(Object value) {
if (value == null)
return null;
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream outputStream;
try {
outputStream = new ObjectOutputStream(arrayOutputStream);
outputStream.writeObject(value);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
arrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return arrayOutputStream.toByteArray();
}
//反序列化方法
public Object byte2Object(byte[] bytes) {
if (bytes == null || bytes.length == 0)
return null;
try {
ObjectInputStream inputStream;
inputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
Object obj = inputStream.readObject();
return obj;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
//保存文件方法
public void setFile(String key,String path){

File fr = new File(path); 
redis.set(key.getBytes(), object2Bytes(fr));
}
//读取文件对象方法
public File getFile(String key){
Jedis redis = new Jedis("localhost");
File file = (File)byte2Object(redis.get(key.getBytes()));
return file;
}

public void testFile(String key,String path)throws Exception{
setFile("test", "D:\\test.txt");
File file = getFile("test");
BufferedReader br = new BufferedReader(new FileReader(file)); 
String record = null; 
while ((record = br.readLine()) != null) { 
System.out.println("record:"+record);
}

}

public static void main(String[] args) throws Exception{
TestRedisos = new TestRedis();
os.testFile("test", "D:\\test.txt");
}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值