Redis - window/linux 安装部署及java简单连接测试demo
1.下载window版本 / 下载Linux版本:https://github.com/MicrosoftArchive/redis/releases
下载window版本(百度网盘):https://pan.baidu.com/s/1au1Hl045H_eXo0_61_VMVw
下载Linux版本(百度网盘): https://pan.baidu.com/s/1jJnbiP31DseuObxviLotNg
2.安装及配置(网上很多,略过)
3.截图左侧是启动Redis界面,右侧是Redis客户端界面及简单的数据存入和取出;
.
4.java连接及存储数据;
1).创建连接池:
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
@Configuration
public class RedisConfig extends CachingConfigurerSupport{
private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class);
//服务器IP地址
private static String ADDR = "127.0.0.1";
//端口
private static int PORT = 6379;
//密码
private static String AUTH = "123456";
//连接实例的最大连接数
private static int MAX_ACTIVE = 1024;
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 200;
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
private static int MAX_WAIT = 100000;
//连接超时的时间
private static int TIMEOUT = 10000;
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
private static ShardedJedisPool shardedJedisPool;
/**
* 初始化Redis连接池
*/
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
//jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
jedisPool = new JedisPool(config,ADDR,PORT,TIMEOUT);
// slave链接 redis拥有16个库,默认使用0(select 0/1/2...)
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(ADDR, PORT, "master"));
// 构造池
shardedJedisPool = new ShardedJedisPool(config, shards);
LOGGER.debug("connecting to Redis Success ! ip: {} port: {}",ADDR,PORT);
} catch (Exception e) {
e.printStackTrace();
}
}
/*@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
//设置序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//配置redisTemplate
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);//key序列化
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);//value序列化
redisTemplate.setHashKeySerializer(stringSerializer);//Hash key序列化
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);//Hash value序列化
redisTemplate.afterPropertiesSet();
return redisTemplate;
}*/
/**
* 获取Jedis实例
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取ShardedJedis实例
*/
public synchronized static ShardedJedis getShardedJedis() {
try {
if (shardedJedisPool != null) {
ShardedJedis shardedJedis = shardedJedisPool.getResource();
return shardedJedis;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/***
*
* 释放资源Jedis
*/
public static void returnResource(final Jedis jedis) {
if(jedis != null) {
//jedis.close(); //new version support
jedisPool.returnResource(jedis);
}
}
/***
*
* 释放资源ShardedJedis
*/
public static void returnResource(final ShardedJedis sharededjedis) {
if(sharededjedis != null) {
//sharededjedis.close(); //new version support
shardedJedisPool.returnResource(sharededjedis);
}
}
}
2).Redis操作工具类:
import java.util.List;
import java.util.Set;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedis;
@Component("redisUtils")
public class RedisUtils {
/**
* Set scard 获取key对应的集合中元素个数
*/
public static Long scard(byte [] key){
Jedis jedis = RedisConfig.getJedis();
Long num = jedis.scard(key);
RedisConfig.returnResource(jedis);
return num;
}
/**
* Set smembers 获取key对应的集合的所有成员
*/
public static Set<byte[]> smembers(byte [] key){
Jedis jedis = RedisConfig.getJedis();
Set<byte[]> result = jedis.smembers(key);
RedisConfig.returnResource(jedis);
return result;
}
/**
* Set sadd key对应的集合中添加元素
*/
public static void sadd(byte [] key,byte [] value){
Jedis jedis = RedisConfig.getJedis();
jedis.sadd(key,value);
RedisConfig.returnResource(jedis);
}
/**
* Set srem 对key对应的集合中删除某些值
*/
public static void srem(byte [] key,byte [] value){
Jedis jedis = RedisConfig.getJedis();
jedis.srem(key,value);
RedisConfig.returnResource(jedis);
}
/**
* Hash hlen 获取key哈希表中字段的数量
*/
public static Long hlen(byte [] key){
ShardedJedis shardedJedis = RedisConfig.getShardedJedis();
Long num = shardedJedis.hlen(key);
RedisConfig.returnResource(shardedJedis);
return num;
}
/**
* Hash hget 获取key哈希表中字段的value
*/
public static byte[] hget(byte [] key,byte [] value){
ShardedJedis shardedJedis = RedisConfig.getShardedJedis();
byte[] result = shardedJedis.hget(key,value);
RedisConfig.returnResource(shardedJedis);
return result;
}
/**
* Hash hget 获取key哈希表中字段的value
*/
public static String hget(String key,String value){
ShardedJedis shardedJedis = RedisConfig.getShardedJedis();
String result = shardedJedis.hget(key,value);
RedisConfig.returnResource(shardedJedis);
return result;
}
/**
* Hash hset 设置key哈希表中字段的value
*/
public static Long hset(byte [] key,byte [] filed,byte [] value){
ShardedJedis shardedJedis = RedisConfig.getShardedJedis();
Long result = shardedJedis.hset(key,filed,value);
RedisConfig.returnResource(shardedJedis);
return result;
}
/**
* Hash hset 设置key哈希表中字段的value
*/
public static Long hset(String key,String filed,String value){
ShardedJedis shardedJedis = RedisConfig.getShardedJedis();
Long result = shardedJedis.hset(key,filed,value);
RedisConfig.returnResource(shardedJedis);
return result;
}
/**
* Hash hdel 删除key哈希表中字段的value
*/
public static Long hdel(byte [] key,byte [] filed){
ShardedJedis shardedJedis = RedisConfig.getShardedJedis();
Long result = shardedJedis.hdel(key,filed);
RedisConfig.returnResource(shardedJedis);
return result;
}
/**
* Hash hdel 删除key哈希表中字段的value
*/
public static Long hdel(String key,String filed){
ShardedJedis shardedJedis = RedisConfig.getShardedJedis();
Long result = shardedJedis.hdel(key,filed);
RedisConfig.returnResource(shardedJedis);
return result;
}
/**
* 通过key删除(字节)
* @param key
*/
public void del(byte [] key){
Jedis jedis = RedisConfig.getJedis();
jedis.del(key);
RedisConfig.returnResource(jedis);
}
/**
* 通过key删除
* @param key
*/
public void del(String key){
Jedis jedis = RedisConfig.getJedis();
jedis.del(key);
RedisConfig.returnResource(jedis);
}
/**
* 添加key value 并且设置存活时间(byte)
* @param key
* @param value
* @param liveTime
*/
public void set(byte [] key,byte [] value,int liveTime){
Jedis jedis = RedisConfig.getJedis();
jedis.set(key, value);
jedis.expire(key, liveTime);
RedisConfig.returnResource(jedis);
}
/**
* 添加key value 并且设置存活时间
* @param key
* @param value
* @param liveTime
*/
public void set(String key,String value,int liveTime){
Jedis jedis = RedisConfig.getJedis();
jedis.set(key, value);
jedis.expire(key, liveTime);
RedisConfig.returnResource(jedis);
}
/**
* 添加key value
* @param key
* @param value
*/
public void set(String key,String value){
Jedis jedis = RedisConfig.getJedis();
jedis.set(key, value);
RedisConfig.returnResource(jedis);
}
/**添加key value (字节)(序列化)
* @param key
* @param value
*/
public void set(byte [] key,byte [] value){
Jedis jedis = RedisConfig.getJedis();
jedis.set(key, value);
RedisConfig.returnResource(jedis);
}
/**
* 获取redis value (String)
* @param key
* @return
*/
public String get(String key){
Jedis jedis = RedisConfig.getJedis();
String value = jedis.get(key);
RedisConfig.returnResource(jedis);
return value;
}
/**
* 获取redis value (byte [] )(反序列化)
* @param key
* @return
*/
public byte[] get(byte [] key){
Jedis jedis = RedisConfig.getJedis();
byte[] value = jedis.get(key);
RedisConfig.returnResource(jedis);
return value;
}
/**
* 通过正则匹配keys
* @param pattern
* @return
*/
public Set<String> keys(String pattern){
Jedis jedis = RedisConfig.getJedis();
Set<String> value = jedis.keys(pattern);
RedisConfig.returnResource(jedis);
return value;
}
/**
* 检查key是否已经存在
* @param key
* @return
*/
public boolean exists(String key){
Jedis jedis = RedisConfig.getJedis();
boolean value = jedis.exists(key);
RedisConfig.returnResource(jedis);
return value;
}
/*******************redis list操作************************/
/**
* 往list中添加元素
* @param key
* @param value
*/
public void lpush(String key,String value){
Jedis jedis = RedisConfig.getJedis();
jedis.lpush(key, value);
RedisConfig.returnResource(jedis);
}
public void rpush(String key,String value){
Jedis jedis = RedisConfig.getJedis();
jedis.rpush(key, value);
RedisConfig.returnResource(jedis);
}
/**
* 数组长度
* @param key
* @return
*/
public Long llen(String key){
Jedis jedis = RedisConfig.getJedis();
Long len = jedis.llen(key);
RedisConfig.returnResource(jedis);
return len;
}
/**
* 获取下标为index的value
* @param key
* @param index
* @return
*/
public String lindex(String key,Long index){
Jedis jedis = RedisConfig.getJedis();
String str = jedis.lindex(key, index);
RedisConfig.returnResource(jedis);
return str;
}
public String lpop(String key){
Jedis jedis = RedisConfig.getJedis();
String str = jedis.lpop(key);
RedisConfig.returnResource(jedis);
return str;
}
public List<String> lrange(String key,long start,long end){
Jedis jedis = RedisConfig.getJedis();
List<String> str = jedis.lrange(key, start, end);
RedisConfig.returnResource(jedis);
return str;
}
/*********************redis list操作结束**************************/
/**
* 清空redis 所有数据
* @return
*/
public String flushDB(){
Jedis jedis = RedisConfig.getJedis();
String str = jedis.flushDB();
RedisConfig.returnResource(jedis);
return str;
}
/**
* 查看redis里有多少数据
*/
public long dbSize(){
Jedis jedis = RedisConfig.getJedis();
long len = jedis.dbSize();
RedisConfig.returnResource(jedis);
return len;
}
/**
* 检查是否连接成功
* @return
*/
public String ping(){
Jedis jedis = RedisConfig.getJedis();
String str = jedis.ping();
RedisConfig.returnResource(jedis);
return str;
}
}
3).测试示例:
①RedisUtil + RedisUtilTest
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
//服务器IP地址
private static String ADDR = "127.0.0.1";
//端口
private static int PORT = 6379;
//密码
private static String AUTH = "123456";
//连接实例的最大连接数
private static int MAX_ACTIVE = 1024;
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 200;
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
private static int MAX_WAIT = 10000;
//连接超时的时间
private static int TIMEOUT = 10000;
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
/**
* 初始化Redis连接池
*/
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
//jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
jedisPool = new JedisPool(config,ADDR,PORT,TIMEOUT);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取Jedis实例
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/***
*
* 释放资源
*/
public static void returnResource(final Jedis jedis) {
if(jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
----------------------------------------------------------------------------------------
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import redis.clients.jedis.Jedis;
public class RedisUtilTest {
private Jedis jedis;
/**
* 连接redis服务器
*/
public void connectRedis() {
jedis = RedisUtil.getJedis();
}
/**
* redis操作字符串
*/
public void testString() {
// 添加数据
jedis.set("name", "daopin");
System.out.println(jedis.get("name"));
// 拼接字符串
jedis.append("name", ".csdn");
System.out.println(jedis.get("name"));
// 删除数据
jedis.del("name");
System.out.println(jedis.get("name"));
// 设置多个键值对
jedis.mset("name", "daopin", "age", "26", "qq", "11223344556677889900");
jedis.incr("age");// 加1操作
System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("qq"));
}
/**
* redis操作map集合
*/
public void testMap() {
// 添加数据
Map<String, String> map = new HashMap<String, String>();
map.put("name", "daopin");
map.put("age", "26");
map.put("qq", "11223344556677889900");
jedis.hmset("user", map);
// 取出users中的Name,执行结果:[minxr]-->注意结果是一个泛型的List
// 第一个参数是存入redis中map对象的key,后面跟的是放入map中对象的key,后面的key可以是多个,是可变的
List<String> rsmap = jedis.hmget("user", "name", "age", "qq");
System.out.println(rsmap);
// 删除map中的某个键值
jedis.hdel("user", "age");
System.out.println(jedis.hmget("user", "age"));// 因为删除了,所以返回的是Null
System.out.println(jedis.hlen("user"));// 返回key为user的键中存放的值的个数2
System.out.println(jedis.exists("user"));// 是否存在key为user的记录,返回true
System.out.println(jedis.hkeys("user"));// 返回map对象中的所有key
System.out.println(jedis.hvals("user"));// 返回map对象中的所有value
Iterator<String> iter = jedis.hkeys("user").iterator();
while (iter.hasNext()) {
String key = iter.next();
System.out.println(key + ":" + jedis.hmget("user", key));
}
}
/**
* redis操作List集合
*/
public void testList() {
// 开始前,先移除所有的内容
jedis.del("java framework");
System.out.println(jedis.lrange("java framework", 0, -1));
// 先向key java framework 中存放三条数据
jedis.lpush("java framework", "spring_boot");
jedis.lpush("java framework", "spring_cloud");
jedis.lpush("java framework", "springMVC");
// 再取出所有数据jedis.lrange是按范围取出
// 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有
System.out.println(jedis.lrange("java framework", 0, -1));
jedis.del("java framework");
jedis.rpush("java framework", "spring_boot");
jedis.rpush("java framework", "spring_cloud");
jedis.rpush("java framework", "springMVC");
System.out.println(jedis.lrange("java framework", 0, -1));
}
/**
* redis操作set集合
*
*/
public void testSet() {
// 添加
jedis.sadd("users", "daopinz0");
jedis.sadd("users", "daopinz1");
jedis.sadd("users", "daopinz2");
jedis.sadd("users", "daopinz3");
jedis.sadd("users", "daopinz4");
// 删除
jedis.srem("users", "daopinz2");
System.out.println(jedis.smembers("users"));// 获取所有加入的value
System.out.println(jedis.sismember("users", "daopinz2"));// 判断who是否是user集合的元素
System.out.println(jedis.srandmember("users"));
System.out.println(jedis.scard("users"));// 返回集合的元素个数
}
/**
* redis排序
*/
public void testSort() {
// jedis 排序
// 注意,此处的rpush和lpush是List的操作。是一个双向链表(但从表现来看的)
jedis.del("z");// 先清除数据,再加入数据进行测试
jedis.rpush("z", "1");
jedis.lpush("z", "6");
jedis.lpush("z", "3");
jedis.lpush("z", "9");
System.out.println(jedis.lrange("z", 0, -1));
System.out.println(jedis.sort("z"));// [1,3,6,9] //输入排序后结果
System.out.println(jedis.lrange("z", 0, -1));
}
/**
* redis连接池
*/
public void testRedisPool() {
RedisUtil.getJedis().set("newname", "daopin");
System.out.println(RedisUtil.getJedis().get("newname"));
}
public static void main(String[] args) {
RedisUtilTest test = new RedisUtilTest();
test.connectRedis();
test.testRedisPool();
test.testSort();
test.testList();
test.testMap();
test.testString();
test.testSet();
}
}
----------------------------------------------------------------------------------------
OutPoint:
daopin
[9, 3, 6, 1]
[1, 3, 6, 9]
[9, 3, 6, 1]
[]
[springMVC, spring_cloud, spring_boot]
[spring_boot, spring_cloud, springMVC]
[daopin, 26, 11223344556677889900]
[null]
2
true
[qq, name]
[11223344556677889900, daopin]
qq:[11223344556677889900]
name:[daopin]
daopin
daopin.csdn
null
daopin-27-11223344556677889900
[daopinz1, daopinz4, daopinz3, daopinz0]
false
daopinz4
4
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.SortingParams;
public class RedisClient {
private Jedis jedis;//非切片额客户端连接
private JedisPool jedisPool;//非切片连接池
private ShardedJedis shardedJedis;//切片额客户端连接
private ShardedJedisPool shardedJedisPool;//切片连接池
public RedisClient()
{
initialPool();
initialShardedPool();
shardedJedis = shardedJedisPool.getResource();
jedis = jedisPool.getResource();
}
/**
* 初始化非切片池
*/
private void initialPool()
{
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
//config.setMaxWait(1000l);
//config.setMaxActive(20);
config.setMaxWaitMillis(10001);
config.setMaxTotal(20);
config.setMaxIdle(5);
config.setTestOnBorrow(false);
jedisPool = new JedisPool(config,"127.0.0.1",6379);
}
/**
* 初始化切片池
*/
private void initialShardedPool()
{
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
//config.setMaxWait(1000l);
//config.setMaxActive(20);
config.setMaxWaitMillis(10000);
config.setMaxTotal(20);
config.setMaxIdle(5);
config.setTestOnBorrow(false);
// slave链接
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo("127.0.0.1", 6379, "master"));
// 构造池
shardedJedisPool = new ShardedJedisPool(config, shards);
}
public void show() {
KeyOperate();
StringOperate();
ListOperate();
SetOperate();
SortedSetOperate();
HashOperate();
jedisPool.returnResource(jedis);
shardedJedisPool.returnResource(shardedJedis);
}
public void test() {
Person0 person0 = new Person0(66, "xiaoming");
Person1 person1 = new Person1(77, "xiaoning");
//jedis.set(SerializeUtil.serialize(person0), SerializeUtil.serialize(person1));
Person1 psn1=(Person1) SerializeUtil.unserialize(jedis.get(SerializeUtil.serialize(person0)));
System.out.println(psn1);
System.out.println("查看key所储存的值的类型:"+jedis.type(SerializeUtil.serialize(person0)));
System.out.println("判断key999键是否存在:"+shardedJedis.exists(SerializeUtil.serialize(person0)));
System.out.println("获取hashs中所有的key:"+shardedJedis.hkeys("hasha"));
System.out.println("获取hashs中所有的key:"+shardedJedis.hkeys("hashs"));
System.out.println("获取hashs中所有的key:"+shardedJedis.hkeys("hashd"));
System.out.println("获取hashs中所有的key:"+shardedJedis.hlen("hashs"));
System.out.println("获取hashs中所有的value:"+shardedJedis.hvals("hasha"));
System.out.println("获取hashs中所有的value:"+shardedJedis.hvals("hashs"));
System.out.println("获取hashs中所有的value:"+shardedJedis.hvals("hashd"));
jedis.sadd("sets", "element000");
jedis.sadd("sets", "element001");
jedis.sadd("sets", "element002");
jedis.sadd("sets", "element003");
jedis.sadd("sets", "element004");
System.out.println("查看sets集合中的所有元素:"+jedis.smembers("sets").contains("element003"));
jedisPool.returnResource(jedis);
shardedJedisPool.returnResource(shardedJedis);
}
private void KeyOperate() {
System.out.println("======================key==========================");
// 清空数据
System.out.println("清空库中所有数据:"+jedis.flushDB());
// 判断key否存在
System.out.println("判断key999键是否存在:"+shardedJedis.exists("key999"));
System.out.println("新增key001,value001键值对:"+shardedJedis.set("key001", "value001"));
System.out.println("判断key001是否存在:"+shardedJedis.exists("key001"));
// 输出系统中所有的key
System.out.println("新增key002,value002键值对:"+shardedJedis.set("key002", "value002"));
System.out.println("系统中所有键如下:");
Set<String> keys = jedis.keys("*");
Iterator<String> it=keys.iterator() ;
while(it.hasNext()){
String key = it.next();
System.out.println(key);
}
// 删除某个key,若key不存在,则忽略该命令。
System.out.println("系统中删除key002: "+jedis.del("key002"));
System.out.println("判断key002是否存在:"+shardedJedis.exists("key002"));
// 设置 key001的过期时间
System.out.println("设置 key001的过期时间为5秒:"+jedis.expire("key001", 5));
try{
Thread.sleep(2000);
}
catch (InterruptedException e){
}
// 查看某个key的剩余生存时间,单位【秒】.永久生存或者不存在的都返回-1
System.out.println("查看key001的剩余生存时间:"+jedis.ttl("key001"));
// 移除某个key的生存时间
System.out.println("移除key001的生存时间:"+jedis.persist("key001"));
System.out.println("查看key001的剩余生存时间:"+jedis.ttl("key001"));
// 查看key所储存的值的类型
System.out.println("查看key所储存的值的类型:"+jedis.type("key001"));
/*
* 一些其他方法:1、修改键名:jedis.rename("key6", "key0");
* 2、将当前db的key移动到给定的db当中:jedis.move("foo", 1)
*/
System.out.println();
}
private void StringOperate() {
System.out.println("======================String_1==========================");
// 清空数据
System.out.println("清空库中所有数据:"+jedis.flushDB());
System.out.println("=============增=============");
jedis.set("key001","value001");
jedis.set("key002","value002");
jedis.set("key003","value003");
System.out.println("已新增的3个键值对如下:");
System.out.println(jedis.get("key001"));
System.out.println(jedis.get("key002"));
System.out.println(jedis.get("key003"));
System.out.println("=============删=============");
System.out.println("删除key003键值对:"+jedis.del("key003"));
System.out.println("获取key003键对应的值:"+jedis.get("key003"));
System.out.println("=============改=============");
//1、直接覆盖原来的数据
System.out.println("直接覆盖key001原来的数据:"+jedis.set("key001","value001-update"));
System.out.println("获取key001对应的新值:"+jedis.get("key001"));
//2、直接覆盖原来的数据
System.out.println("在key002原来值后面追加:"+jedis.append("key002","+appendString"));
System.out.println("获取key002对应的新值"+jedis.get("key002"));
System.out.println("=============增,删,查(多个)=============");
/**
* mset,mget同时新增,修改,查询多个键值对
* 等价于:
* jedis.set("name","ssss");
* jedis.set("jarorwar","xxxx");
*/
System.out.println("一次性新增key201,key202,key203,key204及其对应值:"+jedis.mset("key201","value201",
"key202","value202","key203","value203","key204","value204"));
System.out.println("一次性获取key201,key202,key203,key204各自对应的值:"+
jedis.mget("key201","key202","key203","key204"));
System.out.println("一次性删除key201,key202:"+jedis.del(new String[]{"key201", "key202"}));
System.out.println("一次性获取key201,key202,key203,key204各自对应的值:"+
jedis.mget("key201","key202","key203","key204"));
System.out.println();
//jedis具备的功能shardedJedis中也可直接使用,下面测试一些前面没用过的方法
System.out.println("======================String_2==========================");
// 清空数据
System.out.println("清空库中所有数据:"+jedis.flushDB());
System.out.println("=============新增键值对时防止覆盖原先值=============");
System.out.println("原先key301不存在时,新增key301:"+shardedJedis.setnx("key301", "value301"));
System.out.println("原先key302不存在时,新增key302:"+shardedJedis.setnx("key302", "value302"));
System.out.println("当key302存在时,尝试新增key302:"+shardedJedis.setnx("key302", "value302_new"));
System.out.println("获取key301对应的值:"+shardedJedis.get("key301"));
System.out.println("获取key302对应的值:"+shardedJedis.get("key302"));
System.out.println("=============超过有效期键值对被删除=============");
// 设置key的有效期,并存储数据
System.out.println("新增key303,并指定过期时间为2秒"+shardedJedis.setex("key303", 2, "key303-2second"));
System.out.println("获取key303对应的值:"+shardedJedis.get("key303"));
try{
Thread.sleep(3000);
}
catch (InterruptedException e){
}
System.out.println("3秒之后,获取key303对应的值:"+shardedJedis.get("key303"));
System.out.println("=============获取原值,更新为新值一步完成=============");
System.out.println("key302原值:"+shardedJedis.getSet("key302", "value302-after-getset"));
System.out.println("key302新值:"+shardedJedis.get("key302"));
System.out.println("=============获取子串=============");
System.out.println("获取key302对应值中的子串:"+shardedJedis.getrange("key302", 5, 7));
System.out.println();
}
private void ListOperate() {
System.out.println("======================list==========================");
// 清空数据
System.out.println("清空库中所有数据:"+jedis.flushDB());
System.out.println("=============增=============");
shardedJedis.lpush("stringlists", "vector");
shardedJedis.lpush("stringlists", "ArrayList");
shardedJedis.lpush("stringlists", "vector");
shardedJedis.lpush("stringlists", "vector");
shardedJedis.lpush("stringlists", "LinkedList");
shardedJedis.lpush("stringlists", "MapList");
shardedJedis.lpush("stringlists", "SerialList");
shardedJedis.lpush("stringlists", "HashList");
shardedJedis.lpush("numberlists", "3");
shardedJedis.lpush("numberlists", "1");
shardedJedis.lpush("numberlists", "5");
shardedJedis.lpush("numberlists", "2");
System.out.println("所有元素-stringlists:"+shardedJedis.lrange("stringlists", 0, -1));
System.out.println("所有元素-numberlists:"+shardedJedis.lrange("numberlists", 0, -1));
System.out.println("=============删=============");
// 删除列表指定的值 ,第二个参数为删除的个数(有重复时),后add进去的值先被删,类似于出栈
System.out.println("成功删除指定元素个数-stringlists:"+shardedJedis.lrem("stringlists", 2, "vector"));
System.out.println("删除指定元素之后-stringlists:"+shardedJedis.lrange("stringlists", 0, -1));
// 删除区间以外的数据
System.out.println("删除下标0-3区间之外的元素:"+shardedJedis.ltrim("stringlists", 0, 3));
System.out.println("删除指定区间之外元素后-stringlists:"+shardedJedis.lrange("stringlists", 0, -1));
// 列表元素出栈
System.out.println("出栈元素:"+shardedJedis.lpop("stringlists"));
System.out.println("元素出栈后-stringlists:"+shardedJedis.lrange("stringlists", 0, -1));
System.out.println("=============改=============");
// 修改列表中指定下标的值
shardedJedis.lset("stringlists", 0, "hello list!");
System.out.println("下标为0的值修改后-stringlists:"+shardedJedis.lrange("stringlists", 0, -1));
System.out.println("=============查=============");
// 数组长度
System.out.println("长度-stringlists:"+shardedJedis.llen("stringlists"));
System.out.println("长度-numberlists:"+shardedJedis.llen("numberlists"));
// 排序
/*
* list中存字符串时必须指定参数为alpha,如果不使用SortingParams,而是直接使用sort("list"),
* 会出现"ERR One or more scores can't be converted into double"
*/
SortingParams sortingParameters = new SortingParams();
sortingParameters.alpha();
sortingParameters.limit(0, 3);
System.out.println("返回排序后的结果-stringlists:"+shardedJedis.sort("stringlists",sortingParameters));
System.out.println("返回排序后的结果-numberlists:"+shardedJedis.sort("numberlists"));
// 子串: start为元素下标,end也为元素下标;-1代表倒数一个元素,-2代表倒数第二个元素
System.out.println("子串-第二个开始到结束:"+shardedJedis.lrange("stringlists", 1, -1));
// 获取列表指定下标的值
System.out.println("获取下标为2的元素:"+shardedJedis.lindex("stringlists", 2)+"\n");
System.out.println();
}
private void SetOperate() {
System.out.println("======================set==========================");
// 清空数据
System.out.println("清空库中所有数据:"+jedis.flushDB());
System.out.println("=============增=============");
System.out.println("向sets集合中加入元素element001:"+jedis.sadd("sets", "element001"));
System.out.println("向sets集合中加入元素element002:"+jedis.sadd("sets", "element002"));
System.out.println("向sets集合中加入元素element003:"+jedis.sadd("sets", "element003"));
System.out.println("向sets集合中加入元素element004:"+jedis.sadd("sets", "element004"));
System.out.println("查看sets集合中的所有元素:"+jedis.smembers("sets"));
System.out.println();
System.out.println("=============删=============");
System.out.println("集合sets中删除元素element003:"+jedis.srem("sets", "element003"));
System.out.println("查看sets集合中的所有元素:"+jedis.smembers("sets"));
/*System.out.println("sets集合中任意位置的元素出栈:"+jedis.spop("sets"));//注:出栈元素位置居然不定?--无实际意义
System.out.println("查看sets集合中的所有元素:"+jedis.smembers("sets"));*/
System.out.println();
System.out.println("=============改=============");
System.out.println();
System.out.println("=============查=============");
System.out.println("判断element001是否在集合sets中:"+jedis.sismember("sets", "element001"));
System.out.println("循环查询获取sets中的每个元素:");
Set<String> set = jedis.smembers("sets");
Iterator<String> it=set.iterator() ;
while(it.hasNext()){
Object obj=it.next();
System.out.println(obj);
}
System.out.println();
System.out.println("=============集合运算=============");
System.out.println("sets1中添加元素element001:"+jedis.sadd("sets1", "element001"));
System.out.println("sets1中添加元素element002:"+jedis.sadd("sets1", "element002"));
System.out.println("sets1中添加元素element003:"+jedis.sadd("sets1", "element003"));
System.out.println("sets1中添加元素element002:"+jedis.sadd("sets2", "element002"));
System.out.println("sets1中添加元素element003:"+jedis.sadd("sets2", "element003"));
System.out.println("sets1中添加元素element004:"+jedis.sadd("sets2", "element004"));
System.out.println("查看sets1集合中的所有元素:"+jedis.smembers("sets1"));
System.out.println("查看sets2集合中的所有元素:"+jedis.smembers("sets2"));
System.out.println("sets1和sets2交集:"+jedis.sinter("sets1", "sets2"));
System.out.println("sets1和sets2并集:"+jedis.sunion("sets1", "sets2"));
System.out.println("sets1和sets2差集:"+jedis.sdiff("sets1", "sets2"));//差集:set1中有,set2中没有的元素
System.out.println();
}
private void SortedSetOperate() {
System.out.println("======================zset==========================");
// 清空数据
System.out.println(jedis.flushDB());
System.out.println("=============增=============");
System.out.println("zset中添加元素element001:"+shardedJedis.zadd("zset", 7.0, "element001"));
System.out.println("zset中添加元素element002:"+shardedJedis.zadd("zset", 8.0, "element002"));
System.out.println("zset中添加元素element003:"+shardedJedis.zadd("zset", 2.0, "element003"));
System.out.println("zset中添加元素element004:"+shardedJedis.zadd("zset", 3.0, "element004"));
System.out.println("zset集合中的所有元素:"+shardedJedis.zrange("zset", 0, -1));//按照权重值排序
System.out.println();
System.out.println("=============删=============");
System.out.println("zset中删除元素element002:"+shardedJedis.zrem("zset", "element002"));
System.out.println("zset集合中的所有元素:"+shardedJedis.zrange("zset", 0, -1));
System.out.println();
System.out.println("=============改=============");
System.out.println();
System.out.println("=============查=============");
System.out.println("统计zset集合中的元素中个数:"+shardedJedis.zcard("zset"));
System.out.println("统计zset集合中权重某个范围内(1.0——5.0),元素的个数:"+shardedJedis.zcount("zset", 1.0, 5.0));
System.out.println("查看zset集合中element004的权重:"+shardedJedis.zscore("zset", "element004"));
System.out.println("查看下标1到2范围内的元素值:"+shardedJedis.zrange("zset", 1, 2));
System.out.println();
}
private void HashOperate() {
System.out.println("======================hash==========================");
//清空数据
System.out.println(jedis.flushDB());
System.out.println("=============增=============");
System.out.println("hashs中添加key001和value001键值对:"+shardedJedis.hset("hashs", "key001", "value001"));
System.out.println("hashs中添加key002和value002键值对:"+shardedJedis.hset("hashs", "key002", "value002"));
System.out.println("hashs中添加key003和value003键值对:"+shardedJedis.hset("hashs", "key003", "value003"));
System.out.println("新增key004和4的整型键值对:"+shardedJedis.hincrBy("hashs", "key004", 4l));
System.out.println("hashs中的所有值:"+shardedJedis.hvals("hashs"));
System.out.println();
System.out.println("=============删=============");
System.out.println("hashs中删除key002键值对:"+shardedJedis.hdel("hashs", "key002"));
System.out.println("hashs中的所有值:"+shardedJedis.hvals("hashs"));
System.out.println();
System.out.println("=============改=============");
System.out.println("key004整型键值的值增加100:"+shardedJedis.hincrBy("hashs", "key004", 100l));
System.out.println("hashs中的所有值:"+shardedJedis.hvals("hashs"));
System.out.println();
System.out.println("=============查=============");
System.out.println("判断key003是否存在:"+shardedJedis.hexists("hashs", "key003"));
System.out.println("获取key004对应的值:"+shardedJedis.hget("hashs", "key004"));
System.out.println("批量获取key001和key003对应的值:"+shardedJedis.hmget("hashs", "key001", "key003"));
System.out.println("获取hashs中所有的key:"+shardedJedis.hkeys("hashs"));
System.out.println("获取hashs中所有的value:"+shardedJedis.hvals("hashs"));
System.out.println();
}
}
----------------------------------------------------------------------------------------
public class RedisTest {
/*
* 几个exe程序的功能:
*
* redis-benchmark.exe:性能测试,用以模拟同时由N个客户端发送M个 SETs/GETs 查询 (类似于 Apache 的ab 工具).
*
* redis-check-aof.exe:更新日志检查
*
* redis-check-dump.exe:本地数据库检查
*
* redis-cli.exe:客户端 redis-server.exe:服务端
*
* start Redis server(windows) .\redis-server.exe .\redis.windows.conf
* start Redis client(windows) .\redis-cli.exe -h 127.0.0.1 -p 6379
*/
public static void main(String[] args) {
new RedisClient().show();
//new RedisClient().test();
}
}
4).JAVA序列化及反序列化工具类:
①IO:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SerializeUtil {
private final static Logger LOGGER = Logger.getLogger(SerializeUtil.class.getCanonicalName());
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) {
LOGGER.log(Level.WARNING,"序列化对象出现异常: ", e.getMessage());
}
return null;
}
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
LOGGER.log(Level.WARNING,"反序列化对象出现异常: ", e.getMessage());
}
return null;
}
//对象序列化为字符串
public static String objectSerialiable(Object obj){
String serStr = null;
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(obj);
serStr = byteArrayOutputStream.toString("ISO-8859-1");
serStr = java.net.URLEncoder.encode(serStr, "UTF-8");
objectOutputStream.close();
byteArrayOutputStream.close();
} catch (UnsupportedEncodingException e) {
LOGGER.log(Level.WARNING,"序列化对象出现异常: ", e.getMessage());
} catch (IOException e) {
LOGGER.log(Level.WARNING,"序列化对象出现异常: ", e.getMessage());
}
return serStr;
}
//字符串反序列化为对象
public static Object objectDeserialization(String serStr){
Object newObj = null;
try {
String redStr = java.net.URLDecoder.decode(serStr, "UTF-8");
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(redStr.getBytes("ISO-8859-1"));
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
newObj = objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();
} catch (UnsupportedEncodingException e) {
LOGGER.log(Level.WARNING,"反序列化对象出现异常: ", e.getMessage());
} catch (ClassNotFoundException e) {
LOGGER.log(Level.WARNING,"反序列化对象出现异常: ", e.getMessage());
} catch (IOException e) {
LOGGER.log(Level.WARNING,"反序列化对象出现异常: ", e.getMessage());
}
return newObj;
}
}
②Jackson:
import java.nio.charset.Charset;
import org.springframework.data.redis.serializer.SerializationException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonRedisSeriaziler {
public static final String EMPTY_JSON = "{}";
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
protected static ObjectMapper objectMapper = new ObjectMapper();
public JsonRedisSeriaziler() {
}
/**
* java-object as json-string
*
* @param object
* @return
*/
public static String seriazileAsString(Object object) {
if (object == null) {
return EMPTY_JSON;
}
try {
return objectMapper.writeValueAsString(object);
} catch (Exception ex) {
throw new SerializationException("Could not write JSON: "
+ ex.getMessage(), ex);
}
}
/**
* json-string to java-object
*
* @param str
* @return
*/
public static <T> T deserializeAsObject(String str, Class<T> clazz) {
if (str == null || clazz == null) {
return null;
}
try {
return objectMapper.readValue(str, clazz);
} catch (Exception ex) {
throw new SerializationException("Could not write JSON: "
+ ex.getMessage(), ex);
}
}
}
③fastjson:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
Javabean 序列化 并存入到Redis;
RedisUtils.hset("testJavabean",JSON.toJSONString(Javabean0), JSON.toJSONString(Javabean1));
Redis 反序列化 到java对象;
Javabean1 javabean1= JSON.parseObject( RedisUtils.hget("testJavabean", JSON.toJSONString(Javabean0)),Javabean1.class);
Redis的简单使用,基本上就是这些;
不过,我现在的问题是,存入Redis的java对象是一个复杂的class,反序列化的时候很多数据都会为空,
例如:Javabean1 里面有
private volatile Javabean2 javabean2 ;
private volatile Javabean3 javabean3 ;
private volatile Javabean4 javabean4 ;
。。。 。。。
这些在反序列化的时候只能拿到Javabean1 自己class里面的参数,其他的javabean2=null; javabean3=null; javabean4=null; ... ...
像这种比较复杂的class类,怎样做持久化到Redis或者Memcache中呢?
继续学习。。。 。。。