Redis登錄,緩存,實現購物車功能

1.登錄和緩存功能實現

package com.redis;

import redis.clients.jedis.Jedis;

/**
 * FileName: 登錄和緩存
 * Author:   sujinran
 * Date:     2018/6/17 15:12
 */
public class LoginAndCookie {
    /**
     * 檢查用戶是否登錄
     * @param conn redis連接
     * @param token 令牌
     * @return
     */
    public String checkToken(Jedis conn, String token) {
        //hget散列
        return conn.hget("login:", token);
    }

    /**
     * 更新令牌
     * @param conn redis連接
     * @param token 令牌
     * @param user 用戶
     * @param item 商品
     */
    public void updateToken(Jedis conn, String token, String user, String item) {
        //獲取當前時間戳
        long timestamp = System.currentTimeMillis() / 1000;
        //令牌和已經登錄的用戶映射
        conn.hset("login:", token, user);
        //記錄令牌最後一次出現的時間
        conn.zadd("recent:", timestamp, token);
        if (item != null) {//傳入的商品不是空的
            //記錄瀏覽過的商品
            conn.zadd("viewed:" + token, timestamp, item);
            //移除舊的記錄,保留最近瀏覽過的25個商品
            conn.zremrangeByRank("viewed:" + token, 0, -26);
            //Zincrby 命令對有序集合中指定成員的分數加上增量
            conn.zincrby("viewed:", -1, item);
        }
    }


}

更新會話:

package com.util;

import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Set;

/**
 * FileName: 更新登錄會話
 * Author:   sujinran
 * Date:     2018/6/17 19:40
 */
public class CleanSessionsThread extends Thread {
    private Jedis conn;
    private int limit;
    private boolean quit;

    public CleanSessionsThread(int limit) {
        this.conn = new Jedis("localhost");
        this.conn.auth("123456");
        this.conn.select(15);
        this.limit = limit;
    }

    public void quit() {
        quit = true;
    }

    public void run() {
        while (!quit) {
            //依據登錄時間確定在線人數
            long size = conn.zcard("recent:");
            if (size <= limit) {
                try {
                    sleep(1000);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
                continue;
            }

            long endIndex = Math.min(size - limit, 100);
            Set<String> tokenSet = conn.zrange("recent:", 0, endIndex - 1);
            String[] tokens = tokenSet.toArray(new String[tokenSet.size()]);

            ArrayList<String> sessionKeys = new ArrayList<String>();
            for (String token : tokens) {
                sessionKeys.add("viewed:" + token);
            }
            conn.del(sessionKeys.toArray(new String[sessionKeys.size()]));
            conn.hdel("login:", tokens);
            conn.zrem("recent:", tokens);
        }
    }
}

登錄和緩存功能測試:

import com.util.CleanSessionsThread;
import com.redis.LoginAndCookie;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import java.util.UUID;

/**
 * FileName: 登錄和緩存測試
 * Author:   sujinran
 * Date:     2018/6/17 19:15
 */
public class LoginAndCookieTest {
    public static void main(String[] args) throws InterruptedException {
        Jedis conn =new Jedis("127.0.0.1");
        conn.auth("123456");
        LoginAndCookieTest loginAndCookieTest =new LoginAndCookieTest();
        loginAndCookieTest.testLoginCookies(conn);
    }
    /**
     * 登錄測試
     *
     * @throws InterruptedException
     */
    public void testLoginCookies(Jedis conn) throws InterruptedException {
        /*
        這裏令牌自動生成
        UUID.randomUUID().toString():javaJDK提供的一個自動生成主鍵的方法
         */
        String token = UUID.randomUUID().toString();
        //創建登錄和緩存類的對象
        LoginAndCookie loginAndCookie = new LoginAndCookie();
        /*
        使用 LoginAndCookie 中的updateToken()的方法更新令牌
        conn:Redis連接,user1:用戶,item1:商品
         */
        loginAndCookie.updateToken(conn, token, "user1", "item1");
        System.out.println("我們剛剛登錄/更新了令牌:" + token);
        System.out.println("用戶使用: 'user1'");
        System.out.println();

        System.out.println("當我們查找令牌時會得到什麼用戶名");
        String r = loginAndCookie.checkToken(conn, token);
        //r是令牌
        System.out.println(r);
        System.out.println();
        assert r != null;

        System.out.println("讓我們把cookies的最大數量降到0來清理它們");
        System.out.println("我們開始用線程來清理,一會兒再停止");

        CleanSessionsThread thread = new CleanSessionsThread(0);
        thread.start();
        Thread.sleep(1000);
        thread.quit();
        Thread.sleep(2000);
        if (thread.isAlive()) {
            throw new RuntimeException("線程還存活?!?");
        }
        //Hlen命令用於獲取哈希表中字段的數量
        long s = conn.hlen("login:");
        System.out.println("目前仍可提供的sessions次數如下: " + s);
        assert s == 0;
    }

}

2.購物車功能實現

package com.redis;

import redis.clients.jedis.Jedis;

/**
 * FileName: 購物車實現
 * Author:   sujinran
 * Date:     2018/6/17 20:27
 */
public class AddToCart {
    /**
     *  購物車實現
     * @param conn 連接
     * @param session 會話
     * @param item 商品
     * @param count 總數
     */
    public void addToCart(Jedis conn, String session, String item, int count) {
        //總數<=0
        if (count <= 0) {
            // 購物車移除指定的商品,HDEL 每次只能刪除單個域
            conn.hdel("cart:" + session, item);
        } else {
            //將指定的商品添加到購物車,Hset 命令用於爲哈希表中的字段賦值
            conn.hset("cart:" + session, item, String.valueOf(count));
        }
    }
}

更新會話:

package com.util;

import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Set;

/**
 * FileName: 更新購物車會話
 * Author:   sujinran
 * Date:     2018/6/17 20:35
 */
public class CleanFullSessionsThread extends Thread {
    private Jedis conn;
    private int limit;
    private boolean quit;

    public CleanFullSessionsThread(int limit) {
        this.conn = new Jedis("localhost");
        this.conn.auth("123456");
        this.conn.select(15);
        this.limit = limit;
    }

    public void quit() {
        quit = true;
    }

    public void run() {
        while (!quit) {
            long size = conn.zcard("recent:");
            if (size <= limit) {
                try {
                    sleep(1000);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
                continue;
            }

            long endIndex = Math.min(size - limit, 100);
            Set<String> sessionSet = conn.zrange("recent:", 0, endIndex - 1);
            String[] sessions = sessionSet.toArray(new String[sessionSet.size()]);

            ArrayList<String> sessionKeys = new ArrayList<String>();
            for (String sess : sessions) {
                sessionKeys.add("viewed:" + sess);
                sessionKeys.add("cart:" + sess);
            }

            conn.del(sessionKeys.toArray(new String[sessionKeys.size()]));
            conn.hdel("login:", sessions);
            conn.zrem("recent:", sessions);
        }
    }
}

購物車功能測試:

import com.redis.AddToCart;
import com.redis.LoginAndCookie;
import com.util.CleanFullSessionsThread;
import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.UUID;

/**
 * FileName: 添加商品到購物車測試
 * Author:   sujinran
 * Date:     2018/6/17 20:39
 */
public class AddToCartTest {
    AddToCart addToCart =new AddToCart();
    LoginAndCookie loginAndCookie =new LoginAndCookie();


    public static void main(String[] args) throws InterruptedException {
        Jedis conn = new Jedis("127.0.0.1");
        conn.auth("123456");
        AddToCartTest addToCartTest =new AddToCartTest();
        addToCartTest.testShopppingCartCookies(conn);
    }
    /**
     * 添加商品到購物車測試
     * @param conn
     * @throws InterruptedException
     */
    public void testShopppingCartCookies(Jedis conn) throws InterruptedException {
         /*
        這裏令牌自動生成
        UUID.randomUUID().toString():javaJDK提供的一個自動生成主鍵的方法
         */
        String token = UUID.randomUUID().toString();

        System.out.println("我們將刷新我們的會話.");
        loginAndCookie.updateToken(conn, token, "user2", "item2");
        System.out.println("並在購物車中添加一個商品");
        addToCart.addToCart(conn, token, "item2", 3);
        Map<String, String> r = conn.hgetAll("cart:" + token);
        System.out.println("我們的購物車目前有:");
        for (Map.Entry<String, String> entry : r.entrySet()) {
            System.out.println("  " + entry.getKey() + ": " + entry.getValue());
        }
        System.out.println();

        assert r.size() >= 1;

        System.out.println("讓我們清理我們的會話和購物車");
        CleanFullSessionsThread thread = new CleanFullSessionsThread(0);
        thread.start();
        Thread.sleep(1000);
        thread.quit();
        Thread.sleep(2000);
        if (thread.isAlive()) {
            throw new RuntimeException("清理會話線程還存在");
        }
        r = conn.hgetAll("cart:" + token);
        System.out.println("我們的購物車現在裝有:");
        for (Map.Entry<String, String> entry : r.entrySet()) {
            System.out.println("  " + entry.getKey() + ": " + entry.getValue());
        }
        assert r.size() == 0;
    }

}

發佈了40 篇原創文章 · 獲贊 27 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章