溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

redis應(yīng)用場(chǎng)景(2)日志記錄及指標(biāo)統(tǒng)計(jì)

發(fā)布時(shí)間:2020-07-25 22:27:52 來源:網(wǎng)絡(luò) 閱讀:11180 作者:randy_shandong 欄目:開發(fā)技術(shù)

使用redis存儲(chǔ)業(yè)務(wù)信息,同時(shí)也可以存儲(chǔ)系統(tǒng)運(yùn)維信息,比如日志和計(jì)數(shù)器來收集系統(tǒng)當(dāng)前的狀態(tài)信息,挖掘正在使用系統(tǒng)的顧客信息,以及診斷系統(tǒng)問題,發(fā)現(xiàn)潛在的問題。當(dāng)然,系統(tǒng)日志信息及統(tǒng)計(jì)信息也可以存儲(chǔ)在關(guān)系型數(shù)據(jù)庫(kù)中,但是存在一個(gè)很大的弊端,影響業(yè)務(wù)性能。


1.使用redis記錄日志

熟悉java的朋友,記錄日志往往采用的是log4j,sl4j,大多記錄載體選擇文本文件。如果使用web集群的話,造成日志分散在各個(gè)web服務(wù)器,搜集有效日志信息,非常麻煩。如果選擇數(shù)據(jù)庫(kù)保存的話,解決了文件分散情況,但勢(shì)必對(duì)業(yè)務(wù)造成影響,日志畢竟是個(gè)輔助支撐而已,不應(yīng)該和業(yè)務(wù)系統(tǒng)相提并論。這時(shí)候,redis是一個(gè)不錯(cuò)的選擇。如果可以的話,可以對(duì)log4j擴(kuò)展,將數(shù)據(jù)保存到redis中,當(dāng)然這不是本章的重點(diǎn)。本章重點(diǎn),主要簡(jiǎn)單討論下如何保存日志。

構(gòu)建一個(gè)系統(tǒng),判斷哪些信息需要被記錄是一件困難的事情,不同的業(yè)務(wù)有不同的需求。但一般的日志信息往往關(guān)注一下方面。

日志時(shí)間,日志內(nèi)容,服務(wù)IP,日志級(jí)別,日志發(fā)生頻率。

1.1redis日志存儲(chǔ)設(shè)計(jì)

redis應(yīng)用場(chǎng)景(2)日志記錄及指標(biāo)統(tǒng)計(jì)

記錄詳情里,可以按要求,增添想要的信息,發(fā)生的類名稱,處理IP等。

1.2代碼

public void logCommon(
        Jedis conn, String name, String message, String severity, int timeout) {
    String commonDest = "common:" + name + ':' + severity;
    String startKey = commonDest + ":start";
    long end = System.currentTimeMillis() + timeout;
    while (System.currentTimeMillis() < end){
        conn.watch(startKey);
        //當(dāng)前所處的小時(shí)數(shù)
        String hourStart = ISO_FORMAT.format(new Date());
        String existing = conn.get(startKey);

        Transaction trans = conn.multi();
        //如果記錄的是上一個(gè)小時(shí)的日志
        if (existing != null && COLLATOR.compare(existing, hourStart) < 0){
            trans.rename(commonDest, commonDest + ":last");
            trans.rename(startKey, commonDest + ":pstart");
            trans.set(startKey, hourStart);
        }else{
            trans.set(startKey, hourStart);
        }
         //日志計(jì)數(shù)器增1
        trans.zincrby(commonDest, 1, message);
        //記錄最近日志詳情
        String recentDest = "recent:" + name + ':' + severity;
        trans.lpush(recentDest, TIMESTAMP.format(new Date()) + ' ' + message);
        trans.ltrim(recentDest, 0, 99);
        List<Object> results = trans.exec();
        // null response indicates that the transaction was aborted due to
        // the watched key changing.
        if (results == null){
            continue;
        }
        return;
    }
}

2.網(wǎng)站點(diǎn)擊量計(jì)數(shù)器統(tǒng)計(jì)

2.1redis計(jì)數(shù)器存儲(chǔ)設(shè)計(jì)

redis應(yīng)用場(chǎng)景(2)日志記錄及指標(biāo)統(tǒng)計(jì)

2.2編碼

//以秒為單位的精度
public static final int[] PRECISION = new int[]{1, 5, 60, 300, 3600, 18000, 86400};
public void updateCounter(Jedis conn, String name, int count, long now){
    Transaction trans = conn.multi();
    //每一次更新,都要更新所有精度的計(jì)數(shù)器
    for (int prec : PRECISION) {
        long pnow = (now / prec) * prec;//當(dāng)前時(shí)間片的開始時(shí)間
        String hash = String.valueOf(prec) + ':' + name;
        trans.zadd("known:", 0, hash);
        trans.hincrBy("count:" + hash, String.valueOf(pnow), count);
    }
    trans.exec();
}

public List<Pair<Integer,Integer>> getCounter(
    Jedis conn, String name, int precision)
{
    String hash = String.valueOf(precision) + ':' + name;
    Map<String,String> data = conn.hgetAll("count:" + hash);
    ArrayList<Pair<Integer,Integer>> results =
        new ArrayList<Pair<Integer,Integer>>();
    for (Map.Entry<String,String> entry : data.entrySet()) {
        results.add(new Pair<Integer,Integer>(
                    Integer.parseInt(entry.getKey()),
                    Integer.parseInt(entry.getValue())));
    }
    Collections.sort(results);
    return results;
}


2.3清楚舊數(shù)據(jù)


流程圖

redis應(yīng)用場(chǎng)景(2)日志記錄及指標(biāo)統(tǒng)計(jì)

代碼

public class CleanCountersThread
    extends Thread
{
    private Jedis conn;
    private int sampleCount = 100;
    private boolean quit;
    private long timeOffset; // used to mimic a time in the future.

    public CleanCountersThread(int sampleCount, long timeOffset){
        this.conn = new Jedis("192.168.163.156");
        this.conn.select(15);
        this.sampleCount = sampleCount;
        this.timeOffset = timeOffset;
    }

    public void quit(){
        quit = true;
    }

    public void run(){
        int passes = 0;
        while (!quit){
            long start = System.currentTimeMillis() + timeOffset;
            int index = 0;
            while (index < conn.zcard("known:")){
                Set<String> hashSet = conn.zrange("known:", index, index);
                index++;
                if (hashSet.size() == 0) {
                    break;
                }
                String hash = hashSet.iterator().next();
                int prec = Integer.parseInt(hash.substring(0, hash.indexOf(':')));
                int bprec = (int)Math.floor(prec / 60);
                if (bprec == 0){
                    bprec = 1;
                }
                if ((passes % bprec) != 0){
                    continue;
                }

                String hkey = "count:" + hash;
                String cutoff = String.valueOf(
                    ((System.currentTimeMillis() + timeOffset) / 1000) - sampleCount * prec);
                ArrayList<String> samples = new ArrayList<String>(conn.hkeys(hkey));
                Collections.sort(samples);
                int remove = bisectRight(samples, cutoff);

                if (remove != 0){
                    conn.hdel(hkey, samples.subList(0, remove).toArray(new String[0]));
                    if (remove == samples.size()){
                        conn.watch(hkey);
                        if (conn.hlen(hkey) == 0) {
                            Transaction trans = conn.multi();
                            trans.zrem("known:", hash);
                            trans.exec();
                            index--;
                        }else{
                            conn.unwatch();
                        }
                    }
                }
            }

            passes++;
            long duration = Math.min(
                (System.currentTimeMillis() + timeOffset) - start + 1000, 60000);
            try {
                sleep(Math.max(60000 - duration, 1000));
            }catch(InterruptedException ie){
                Thread.currentThread().interrupt();
            }
        }
    }

    // mimic python's bisect.bisect_right
    public int bisectRight(List<String> values, String key) {
        int index = Collections.binarySearch(values, key);
        return index < 0 ? Math.abs(index) - 1 : index + 1;
    }
}

3.使用redis統(tǒng)計(jì)數(shù)據(jù)

上面提到的計(jì)數(shù)器,是最簡(jiǎn)單的統(tǒng)計(jì)數(shù)據(jù)。除了計(jì)數(shù)器(count(*)),還是最大值(max),最小值(min).

設(shè)計(jì)

redis應(yīng)用場(chǎng)景(2)日志記錄及指標(biāo)統(tǒng)計(jì)

stats:模塊(頁(yè)面)名稱:指標(biāo)名稱

public List<Object> updateStats(Jedis conn, String context, String type, double value){
    int timeout = 5000;
    String destination = "stats:" + context + ':' + type;
    String startKey = destination + ":start";
    long end = System.currentTimeMillis() + timeout;
    while (System.currentTimeMillis() < end){
        conn.watch(startKey);
        String hourStart = ISO_FORMAT.format(new Date());

        String existing = conn.get(startKey);
        Transaction trans = conn.multi();
        if (existing != null && COLLATOR.compare(existing, hourStart) < 0){
            trans.rename(destination, destination + ":last");
            trans.rename(startKey, destination + ":pstart");
            trans.set(startKey, hourStart);
        }
        //借助redis提供的最大值,最小值計(jì)算        
        String tkey1 = UUID.randomUUID().toString();
        String tkey2 = UUID.randomUUID().toString();
        trans.zadd(tkey1, value, "min");
        trans.zadd(tkey2, value, "max");

        trans.zunionstore(
            destination,
            new ZParams().aggregate(ZParams.Aggregate.MIN),
            destination, tkey1);
        trans.zunionstore(
            destination,
            new ZParams().aggregate(ZParams.Aggregate.MAX),
            destination, tkey2);

        trans.del(tkey1, tkey2);
        trans.zincrby(destination, 1, "count");
        trans.zincrby(destination, value, "sum");
        trans.zincrby(destination, value * value, "sumsq");

        List<Object> results = trans.exec();
        if (results == null){
            continue;
        }
        return results.subList(results.size() - 3, results.size());
    }
    return null;
}

需要注意的使用redis自帶的最大值最小值,計(jì)算,所以創(chuàng)建了2個(gè)臨時(shí)有序集合。其他的邏輯參照日志相關(guān)部分。


參考內(nèi)容

《redis in action》


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI