本文為大家分享了Redis實(shí)現(xiàn)信息已讀未讀狀態(tài)提示的關(guān)鍵代碼,希望可以給大家一些啟發(fā),具體內(nèi)容如下
前提:
假如現(xiàn)在有2個(gè)模塊需要提示消息:只要存在用戶在上個(gè)時(shí)間點(diǎn)之后沒有看過的信息就提示用戶有新的信息
思路如下:
使用hash存儲用戶上次看過的時(shí)間,使用sortedset存儲每個(gè)模塊的每個(gè)信息產(chǎn)生的時(shí)間
上代碼:
- Map<String, String> dataMap = new HashMap<>();
- Jedis jedis=null;
- String uid="1";//用戶id
- //分類數(shù)組
- String []cagoryArray={"c1","c2"};
- try {
- //連接池獲取連接 jedis=
- //此處獲取用戶的操作時(shí)間集合
- Map<String, String> map = jedis.hgetAll("u-key-"+uid);
- if (map == null) {
- map = new HashMap<>();
- }
- for (String value : cagoryArray) {
- //獲取某個(gè)分類下的上次操作時(shí)間
- String s = map.get(value);
- if (StringUtils.isBlank(s)) {
- //如果不存在,則設(shè)為有新信息
- dataMap.put(value, "1");
- } else {
- //計(jì)算從上次操作時(shí)間到現(xiàn)在的新的信息數(shù)量
- Long zcount = jedis.zcount("c-key-"+value, Double.parseDouble(s), System.currentTimeMillis());
- if (zcount == null || zcount <= 0) {
- //不存在或者小于等于0 則沒有新的信息
- dataMap.put(value, "0");
- } else {
- dataMap.put(value, "1");
- }
- }
- }
- }finally {
- if(jedis!=null){
- //歸還連接
- }
- }
當(dāng)有新的信息產(chǎn)生,向相關(guān)模塊添加時(shí)間:
- Jedis jedis=null;
- //c1模塊有新的信息
- String cid="c1";
- try {
- //連接池獲取連接 jedis=
- //添加到sortedset結(jié)果 權(quán)重為時(shí)間毫秒
- long currentTimeMillis = System.currentTimeMillis();
- jedis.zadd("c-key-"+cid, currentTimeMillis, String.valueOf(currentTimeMillis));
- }finally {
- if(jedis!=null){
- //歸還連接
- }
- }
當(dāng)用戶點(diǎn)擊某個(gè)模塊時(shí),更新用戶查看該模塊的上次時(shí)間:
- Jedis jedis=null;
- //c1模塊有新的信息
- String cid="c1";
- //用戶id
- String uid="1";
- try {
- //連接池獲取連接 jedis=
- //添加到sortedset結(jié)果 權(quán)重為時(shí)間毫秒
- jedis.hset("u-key-"+uid, cid, String.valueOf(System.currentTimeMillis()));
- }finally {
- if(jedis!=null){
- //歸還連接
- }
- }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。