1. 程式人生 > >Redis保證事務一致性,以及常用的數據結構

Redis保證事務一致性,以及常用的數據結構

cor nio osi tel res for class aps 並集

reids命令可以參考中文官網:http://redis.cn/commands.html

關於reids的使用,可以封裝到工具類進行調用:

Redis的工具類:JedisAdapter

技術分享圖片View Code
除了數據結構:reids還可以用來保持事務的一致性;例如:

1:關於Redis的事務:利用reids的exec命令保證執行,不然就discard回滾
例如聲明兩個方法:
Transaction multi(Jedis jedis)
List<Object> exec(Transaction tx, Jedis jedis)
技術分享圖片
    public Transaction multi(Jedis jedis) {
                
try { return jedis.multi(); } catch (Exception e) { logger.error("發生異常" + e.getMessage()); } finally { } return null; } public List<Object> exec(Transaction tx, Jedis jedis) {
try { return tx.exec(); //保證事務執行 } catch (Exception e) { logger.error("發生異常" + e.getMessage()); tx.discard(); //回滾 } finally { if (tx != null) { try { tx.close(); }
catch (IOException ioe) { // .. } } if (jedis != null) { jedis.close(); } } return null; }
View Code

2:對於兩個方法的使用:

 public boolean follow(int userId, int entityType, int entityId) {
        String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);
        String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
        Date date = new Date();
        // 實體的粉絲增加當前用戶
        Jedis jedis = jedisAdapter.getJedis();
        Transaction tx = jedisAdapter.multi(jedis);
        tx.zadd(followerKey, date.getTime(), String.valueOf(userId));
        // 當前用戶對這類實體關註+1
        tx.zadd(followeeKey, date.getTime(), String.valueOf(entityId));
        List<Object> ret = jedisAdapter.exec(tx, jedis);
        return ret.size() == 2 && (Long) ret.get(0) > 0 && (Long) ret.get(1) > 0;
    }
followee/follower兩個隊列
 

3:常見的redis數據結構和使用:

   List:雙向列表,適用於最新列表,關註列表
lpush
lpop
blpop
lindex
lrange
lrem
linsert
lset
rpush
Set:適用於無順序的集合,點贊點踩,抽獎,已讀,共同好友

sdiff
smembers
sinter
scard
SortedSet:排行榜,優先隊列

zadd
zscore
zrange
zcount
zrank
zrevrank
Hash:對象屬性,不定長屬性數

hset
hget
hgetAll
hexists
hkeys
hvals
KV:單一數值,驗證碼,PV,緩存
set
setex
incr
技術分享圖片
Jedis jedis = new Jedis("redis://localhost:6379/9");
jedis.flushDB();

// get set
jedis.set("hello", "world");
print(1, jedis.get("hello"));
jedis.rename("hello", "newhello");
print(1, jedis.get("newhello"));
jedis.setex("hello2", 1800, "world");

//
jedis.set("pv", "100");
jedis.incr("pv");
jedis.incrBy("pv", 5);//一次加五
print(2, jedis.get("pv"));
jedis.decrBy("pv", 2);
print(2, jedis.get("pv"));

print(3, jedis.keys("*"));//打印出來所有的key


//
String listName = "list";
jedis.del(listName);
for (int i = 0; i < 10; ++i) {
    jedis.lpush(listName, "a" + String.valueOf(i));
}
print(4, jedis.lrange(listName, 0, 12));
print(4, jedis.lrange(listName, 0, 3));
print(5, jedis.llen(listName));//長度
print(6, jedis.lpop(listName));//先進後出,pop
print(7, jedis.llen(listName));//長度
print(8, jedis.lrange(listName, 2, 6));
print(9, jedis.lindex(listName, 3));
print(10, jedis.linsert(listName, BinaryClient.LIST_POSITION.AFTER, "a4", "xx"));//插入
print(10, jedis.linsert(listName, BinaryClient.LIST_POSITION.BEFORE, "a4", "bb"));//刪除
print(11, jedis.lrange(listName, 0 ,12)) ;

// hash
String userKey = "userxx";
jedis.hset(userKey, "name", "jim");
jedis.hset(userKey, "age", "12");
jedis.hset(userKey, "phone", "18618181818");
print(12, jedis.hget(userKey, "name"));
print(13, jedis.hgetAll(userKey));
jedis.hdel(userKey, "phone");
print(14, jedis.hgetAll(userKey));
print(15, jedis.hexists(userKey, "email"));
print(16, jedis.hexists(userKey, "age"));
print(17, jedis.hkeys(userKey));
print(18, jedis.hvals(userKey));
jedis.hsetnx(userKey, "school", "zju");
jedis.hsetnx(userKey, "name", "yxy");
print(19, jedis.hgetAll(userKey));

// set集和
String likeKey1 = "commentLike1";
String likeKey2 = "commentLike2";
for (int i = 0; i < 10; ++i) {
    jedis.sadd(likeKey1, String.valueOf(i));
    jedis.sadd(likeKey2, String.valueOf(i*i));
}
print(20, jedis.smembers(likeKey1)); //smembers(key)取值
print(21, jedis.smembers(likeKey2));
print(22, jedis.sunion(likeKey1, likeKey2));//求並集
print(23, jedis.sdiff(likeKey1, likeKey2)); //補集
print(24, jedis.sinter(likeKey1, likeKey2));//交集
print(25, jedis.sismember(likeKey1, "12"));//判斷是否存在
print(26, jedis.sismember(likeKey2, "16"));//判斷
jedis.srem(likeKey1, "5");
print(27, jedis.smembers(likeKey1));
jedis.smove(likeKey2, likeKey1, "25"); //從一移進2一個25
print(28, jedis.smembers(likeKey1));
print(29, jedis.scard(likeKey1)); //求總和

String rankKey = "rankKey";//優先隊列zset()
jedis.zadd(rankKey, 15, "jim");
jedis.zadd(rankKey, 60, "Ben");
jedis.zadd(rankKey, 90, "Lee");
jedis.zadd(rankKey, 75, "Lucy");
jedis.zadd(rankKey, 80, "Mei");
print(30, jedis.zcard(rankKey));// zcard()輸出
print(31, jedis.zcount(rankKey, 61, 100));
print(32, jedis.zscore(rankKey, "Lucy"));
jedis.zincrby(rankKey, 2, "Lucy");
print(33, jedis.zscore(rankKey, "Lucy"));
jedis.zincrby(rankKey, 2, "Luc");
print(34, jedis.zscore(rankKey, "Luc"));
print(35, jedis.zrange(rankKey, 0, 100));
print(36, jedis.zrange(rankKey, 0, 10));//範圍輸出
print(36, jedis.zrange(rankKey, 1, 3));
print(36, jedis.zrevrange(rankKey, 1, 3));//從低到高排列
for (Tuple tuple : jedis.zrangeByScoreWithScores(rankKey, "60", "100")) {
    print(37, tuple.getElement() + ":" + String.valueOf(tuple.getScore()));
}

print(38, jedis.zrank(rankKey, "Ben"));
print(39, jedis.zrevrank(rankKey, "Ben"));

String setKey = "zset";
jedis.zadd(setKey, 1, "a");
jedis.zadd(setKey, 1, "b");
jedis.zadd(setKey, 1, "c");
jedis.zadd(setKey, 1, "d");
jedis.zadd(setKey, 1, "e");

print(40, jedis.zlexcount(setKey, "-", "+"));
print(41, jedis.zlexcount(setKey, "(b", "[d"));//不包含
print(42, jedis.zlexcount(setKey, "[b", "[d"));//包含,b到d
jedis.zrem(setKey, "b");
print(43, jedis.zrange(setKey, 0, 10));
jedis.zremrangeByLex(setKey, "(c", "+");
print(44, jedis.zrange(setKey, 0 ,2));

/*連接池
JedisPool pool = new JedisPool();
for (int i = 0; i < 100; ++i) {
    Jedis j = pool.getResource();
    print(45, j.get("pv"));
    j.close();
}*/

User user = new User();
user.setName("xx");
user.setPassword("ppp");
user.setHeadUrl("a.png");
user.setSalt("salt");
user.setId(1);
print(46, JSONObject.toJSONString(user));//序列化user
jedis.set("user1", JSONObject.toJSONString(user));

String value = jedis.get("user1");
User user2 = JSON.parseObject(value, User.class);//反序列化,轉化為user對象;
print(47, user2);
int k = 2;
View Code

Redis保證事務一致性,以及常用的數據結構