redis只支持string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合)。
实际工作中要存对象,就需要把对象序列化后存入或转化成json字符串
redis 常用命令:
查看当前库里有多少key: dbsize
清除当前库的所有key: flushdb
key 很多时,不要轻易使用keys *,否则容易把生产环境搞死
duckservice:
public List<Duck> selectAllDuck(){
List<Duck> ducks = new ArrayList<>();
long beginTime = System.currentTimeMillis();
Duck duck = new Duck();
for(int i =0;i<100000;i++){
duck.setDuckName(""+i);
duck.setDucknum(""+i);
duck.setServiceMoney(new BigDecimal(i+""));
duck.setJointime(LocalDateTime.now());
ducks.add(duck);
}
long endTime = System.currentTimeMillis();
System.out.println("共创建"+ducks.size()+"对象,用时"+(endTime-beginTime));
return ducks;
}
test:
//redis存储对象
public void redisSaveObj(){
List<Duck> ducks = duckService.selectAllDuck();
Jedis jedis = new Jedis("127.0.0.1",6379,10000);
long beginTime = System.currentTimeMillis();
for(Duck duck:ducks){
byte[] bytes = SerializeUtil.serialize(duck);
jedis.set(duck.getDucknum().getBytes(), bytes);
}
long endTime = System.currentTimeMillis();
System.out.println("共序列+反序列化"+ducks.size()+"对象,用时"+(endTime-beginTime));
System.out.println("从redis get key后反序列化结果!!!:"+SerializeUtil.unserialize(jedis.get("1".getBytes())));
}
serializeUtil:
public class SerializeUtil {
public static byte[] serialize(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) {
}
return null;
}
public static Object unserialize( byte[] bytes) {
if(bytes==null){
System.out.println("反序列化时的字节是空");
return null;
}
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
System.out.println("faslecatch");
}
System.out.println("false");
return null;
}
附带:
redisPool 连接池
JedisPoolConfig poolConfig = new JedisPoolConfig();
//最大空闲数
poolConfig.setMaxIdle(50);
//最大连接数
poolConfig.setMaxTotal(100);
//最大等待毫秒数
poolConfig.setMaxWaitMillis(20000);
//*使用配置创建连接池
JedisPool pool = new JedisPool(poolConfig,"127.0.0.1",6379);
//*从连接池中获取单个连接
Jedis jedis = pool.getResource();