Redis登录,缓存,实现购物车功能

本文展示了如何利用Redis实现登录验证和缓存功能,包括检查和更新令牌,以及清理过期会话。同时,讲解了购物车功能的实现,通过添加、删除商品到购物车,并进行会话清理的测试。所有操作都基于Redis的哈希、有序集合等数据结构。
摘要由CSDN通过智能技术生成

1.登录和缓存功能实现

[java]  view plain  copy
  1. package com.redis;  
  2.   
  3. import redis.clients.jedis.Jedis;  
  4.   
  5. /** 
  6.  * FileName: 登录和缓存 
  7.  * Author:   sujinran 
  8.  * Date:     2018/6/17 15:12 
  9.  */  
  10. public class LoginAndCookie {  
  11.     /** 
  12.      * 检查用户是否登录 
  13.      * @param conn redis连接 
  14.      * @param token 令牌 
  15.      * @return 
  16.      */  
  17.     public String checkToken(Jedis conn, String token) {  
  18.         //hget散列  
  19.         return conn.hget("login:", token);  
  20.     }  
  21.   
  22.     /** 
  23.      * 更新令牌 
  24.      * @param conn redis连接 
  25.      * @param token 令牌 
  26.      * @param user 用户 
  27.      * @param item 商品 
  28.      */  
  29.     public void updateToken(Jedis conn, String token, String user, String item) {  
  30.         //获取当前时间戳  
  31.         long timestamp = System.currentTimeMillis() / 1000;  
  32.         //令牌和已经登录的用户映射  
  33.         conn.hset("login:", token, user);  
  34.         //记录令牌最后一次出现的时间  
  35.         conn.zadd("recent:", timestamp, token);  
  36.         if (item != null) {//传入的商品不是空的  
  37.             //记录浏览过的商品  
  38.             conn.zadd("viewed:" + token, timestamp, item);  
  39.             //移除旧的记录,保留最近浏览过的25个商品  
  40.             conn.zremrangeByRank("viewed:" + token, 0, -26);  
  41.             //Zincrby 命令对有序集合中指定成员的分数加上增量  
  42.             conn.zincrby("viewed:", -1, item);  
  43.         }  
  44.     }  
  45.   
  46.   
  47. }  

更新会话:

[java]  view plain  copy
  1. package com.util;  
  2.   
  3. import redis.clients.jedis.Jedis;  
  4.   
  5. import java.util.ArrayList;  
  6. import java.util.Set;  
  7.   
  8. /** 
  9.  * FileName: 更新登录会话 
  10.  * Author:   sujinran 
  11.  * Date:     2018/6/17 19:40 
  12.  */  
  13. public class CleanSessionsThread extends Thread {  
  14.     private Jedis conn;  
  15.     private int limit;  
  16.     private boolean quit;  
  17.   
  18.     public CleanSessionsThread(int limit) {  
  19.         this.conn = new Jedis("localhost");  
  20.         this.conn.auth("123456");  
  21.         this.conn.select(15);  
  22.         this.limit = limit;  
  23.     }  
  24.   
  25.     public void quit() {  
  26.         quit = true;  
  27.     }  
  28.   
  29.     public void run() {  
  30.         while (!quit) {  
  31.             //依据登录时间确定在线人数  
  32.             long size = conn.zcard("recent:");  
  33.             if (size <= limit) {  
  34.                 try {  
  35.                     sleep(1000);  
  36.                 } catch (InterruptedException ie) {  
  37.                     Thread.currentThread().interrupt();  
  38.                 }  
  39.                 continue;  
  40.             }  
  41.   
  42.             long endIndex = Math.min(size - limit, 100);  
  43.             Set<String> tokenSet = conn.zrange("recent:"0, endIndex - 1);  
  44.             String[] tokens = tokenSet.toArray(new String[tokenSet.size()]);  
  45.   
  46.             ArrayList<String> sessionKeys = new ArrayList<String>();  
  47.             for (String token : tokens) {  
  48.                 sessionKeys.add("viewed:" + token);  
  49.             }  
  50.             conn.del(sessionKeys.toArray(new String[sessionKeys.size()]));  
  51.             conn.hdel("login:", tokens);  
  52.             conn.zrem("recent:", tokens);  
  53.         }  
  54.     }  
  55. }  

登录和缓存功能测试:

[java]  view plain  copy
  1. import com.util.CleanSessionsThread;  
  2. import com.redis.LoginAndCookie;  
  3. import org.junit.Test;  
  4. import redis.clients.jedis.Jedis;  
  5. import java.util.UUID;  
  6.   
  7. /** 
  8.  * FileName: 登录和缓存测试 
  9.  * Author:   sujinran 
  10.  * Date:     2018/6/17 19:15 
  11.  */  
  12. public class LoginAndCookieTest {  
  13.     public static void main(String[] args) throws InterruptedException {  
  14.         Jedis conn =new Jedis("127.0.0.1");  
  15.         conn.auth("123456");  
  16.         LoginAndCookieTest loginAndCookieTest =new LoginAndCookieTest();  
  17.         loginAndCookieTest.testLoginCookies(conn);  
  18.     }  
  19.     /** 
  20.      * 登录测试 
  21.      * 
  22.      * @throws InterruptedException 
  23.      */  
  24.     public void testLoginCookies(Jedis conn) throws InterruptedException {  
  25.         /* 
  26.         这里令牌自动生成 
  27.         UUID.randomUUID().toString():javaJDK提供的一个自动生成主键的方法 
  28.          */  
  29.         String token = UUID.randomUUID().toString();  
  30.         //创建登录和缓存类的对象  
  31.         LoginAndCookie loginAndCookie = new LoginAndCookie();  
  32.         /* 
  33.         使用 LoginAndCookie 中的updateToken()的方法更新令牌 
  34.         conn:Redis连接,user1:用户,item1:商品 
  35.          */  
  36.         loginAndCookie.updateToken(conn, token, "user1""item1");  
  37.         System.out.println("我们刚刚登录/更新了令牌:" + token);  
  38.         System.out.println("用户使用: 'user1'");  
  39.         System.out.println();  
  40.   
  41.         System.out.println("当我们查找令牌时会得到什么用户名");  
  42.         String r = loginAndCookie.checkToken(conn, token);  
  43.         //r是令牌  
  44.         System.out.println(r);  
  45.         System.out.println();  
  46.         assert r != null;  
  47.   
  48.         System.out.println("让我们把cookies的最大数量降到0来清理它们");  
  49.         System.out.println("我们开始用线程来清理,一会儿再停止");  
  50.   
  51.         CleanSessionsThread thread = new CleanSessionsThread(0);  
  52.         thread.start();  
  53.         Thread.sleep(1000);  
  54.         thread.quit();  
  55.         Thread.sleep(2000);  
  56.         if (thread.isAlive()) {  
  57.             throw new RuntimeException("线程还存活?!?");  
  58.         }  
  59.         //Hlen命令用于获取哈希表中字段的数量  
  60.         long s = conn.hlen("login:");  
  61.         System.out.println("目前仍可提供的sessions次数如下: " + s);  
  62.         assert s == 0;  
  63.     }  
  64.   
  65. }  

2.购物车功能实现

[java]  view plain  copy
  1. package com.redis;  
  2.   
  3. import redis.clients.jedis.Jedis;  
  4.   
  5. /** 
  6.  * FileName: 购物车实现 
  7.  * Author:   sujinran 
  8.  * Date:     2018/6/17 20:27 
  9.  */  
  10. public class AddToCart {  
  11.     /** 
  12.      *  购物车实现 
  13.      * @param conn 连接 
  14.      * @param session 会话 
  15.      * @param item 商品 
  16.      * @param count 总数 
  17.      */  
  18.     public void addToCart(Jedis conn, String session, String item, int count) {  
  19.         //总数<=0  
  20.         if (count <= 0) {  
  21.             // 购物车移除指定的商品,HDEL 每次只能删除单个域  
  22.             conn.hdel("cart:" + session, item);  
  23.         } else {  
  24.             //将指定的商品添加到购物车,Hset 命令用于为哈希表中的字段赋值  
  25.             conn.hset("cart:" + session, item, String.valueOf(count));  
  26.         }  
  27.     }  
  28. }  

更新会话:

[java]  view plain  copy
  1. package com.util;  
  2.   
  3. import redis.clients.jedis.Jedis;  
  4.   
  5. import java.util.ArrayList;  
  6. import java.util.Set;  
  7.   
  8. /** 
  9.  * FileName: 更新购物车会话 
  10.  * Author:   sujinran 
  11.  * Date:     2018/6/17 20:35 
  12.  */  
  13. public class CleanFullSessionsThread extends Thread {  
  14.     private Jedis conn;  
  15.     private int limit;  
  16.     private boolean quit;  
  17.   
  18.     public CleanFullSessionsThread(int limit) {  
  19.         this.conn = new Jedis("localhost");  
  20.         this.conn.auth("123456");  
  21.         this.conn.select(15);  
  22.         this.limit = limit;  
  23.     }  
  24.   
  25.     public void quit() {  
  26.         quit = true;  
  27.     }  
  28.   
  29.     public void run() {  
  30.         while (!quit) {  
  31.             long size = conn.zcard("recent:");  
  32.             if (size <= limit) {  
  33.                 try {  
  34.                     sleep(1000);  
  35.                 } catch (InterruptedException ie) {  
  36.                     Thread.currentThread().interrupt();  
  37.                 }  
  38.                 continue;  
  39.             }  
  40.   
  41.             long endIndex = Math.min(size - limit, 100);  
  42.             Set<String> sessionSet = conn.zrange("recent:"0, endIndex - 1);  
  43.             String[] sessions = sessionSet.toArray(new String[sessionSet.size()]);  
  44.   
  45.             ArrayList<String> sessionKeys = new ArrayList<String>();  
  46.             for (String sess : sessions) {  
  47.                 sessionKeys.add("viewed:" + sess);  
  48.                 sessionKeys.add("cart:" + sess);  
  49.             }  
  50.   
  51.             conn.del(sessionKeys.toArray(new String[sessionKeys.size()]));  
  52.             conn.hdel("login:", sessions);  
  53.             conn.zrem("recent:", sessions);  
  54.         }  
  55.     }  
  56. }  

购物车功能测试:

[java]  view plain  copy
  1. import com.redis.AddToCart;  
  2. import com.redis.LoginAndCookie;  
  3. import com.util.CleanFullSessionsThread;  
  4. import redis.clients.jedis.Jedis;  
  5.   
  6. import java.util.Map;  
  7. import java.util.UUID;  
  8.   
  9. /** 
  10.  * FileName: 添加商品到购物车测试 
  11.  * Author:   sujinran 
  12.  * Date:     2018/6/17 20:39 
  13.  */  
  14. public class AddToCartTest {  
  15.     AddToCart addToCart =new AddToCart();  
  16.     LoginAndCookie loginAndCookie =new LoginAndCookie();  
  17.   
  18.   
  19.     public static void main(String[] args) throws InterruptedException {  
  20.         Jedis conn = new Jedis("127.0.0.1");  
  21.         conn.auth("123456");  
  22.         AddToCartTest addToCartTest =new AddToCartTest();  
  23.         addToCartTest.testShopppingCartCookies(conn);  
  24.     }  
  25.     /** 
  26.      * 添加商品到购物车测试 
  27.      * @param conn 
  28.      * @throws InterruptedException 
  29.      */  
  30.     public void testShopppingCartCookies(Jedis conn) throws InterruptedException {  
  31.          /* 
  32.         这里令牌自动生成 
  33.         UUID.randomUUID().toString():javaJDK提供的一个自动生成主键的方法 
  34.          */  
  35.         String token = UUID.randomUUID().toString();  
  36.   
  37.         System.out.println("我们将刷新我们的会话.");  
  38.         loginAndCookie.updateToken(conn, token, "user2""item2");  
  39.         System.out.println("并在购物车中添加一个商品");  
  40.         addToCart.addToCart(conn, token, "item2"3);  
  41.         Map<String, String> r = conn.hgetAll("cart:" + token);  
  42.         System.out.println("我们的购物车目前有:");  
  43.         for (Map.Entry<String, String> entry : r.entrySet()) {  
  44.             System.out.println("  " + entry.getKey() + ": " + entry.getValue());  
  45.         }  
  46.         System.out.println();  
  47.   
  48.         assert r.size() >= 1;  
  49.   
  50.         System.out.println("让我们清理我们的会话和购物车");  
  51.         CleanFullSessionsThread thread = new CleanFullSessionsThread(0);  
  52.         thread.start();  
  53.         Thread.sleep(1000);  
  54.         thread.quit();  
  55.         Thread.sleep(2000);  
  56.         if (thread.isAlive()) {  
  57.             throw new RuntimeException("清理会话线程还存在");  
  58.         }  
  59.         r = conn.hgetAll("cart:" + token);  
  60.         System.out.println("我们的购物车现在装有:");  
  61.         for (Map.Entry<String, String> entry : r.entrySet()) {  
  62.             System.out.println("  " + entry.getKey() + ": " + entry.getValue());  
  63.         }  
  64.         assert r.size() == 0;  
  65.     }  
  66.   
  67. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值