package redis.inaction;

 import redis.clients.jedis.Jedis;
import redis.clients.jedis.ZParams; import java.util.*; public class Chapter01 {
private static final int ONE_WEEK_IN_SECONDS = 7 * 86400;
private static final int VOTE_SCORE = 432;
private static final int ARTICLES_PER_PAGE = 25; public static final void main(String[] args) {
new Chapter01().run();
} public void run() {
Jedis conn = new Jedis("192.168.7.146",6379);
conn.select(15);
conn.flushAll();
String articleId = postArticle(
conn, "username", "A title", "http://www.google.com");
System.out.println("We posted a new article with id: " + articleId);
System.out.println("Its HASH looks like:");
Map<String,String> articleData = conn.hgetAll("article:" + articleId);
for (Map.Entry<String,String> entry : articleData.entrySet()){
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
} System.out.println(); articleVote(conn, "other_user", "article:" + articleId);
String votes = conn.hget("article:" + articleId, "votes");
System.out.println("We voted for the article, it now has votes: " + votes);
assert Integer.parseInt(votes) > 1; System.out.println("The currently highest-scoring articles are:");
List<Map<String,String>> articles = getArticles(conn, 1);
printArticles(articles);
assert articles.size() >= 1; addGroups(conn, articleId, new String[]{"new-group"});
System.out.println("We added the article to a new group, other articles include:");
articles = getGroupArticles(conn, "new-group", 1);
printArticles(articles);
assert articles.size() >= 1;
} public String postArticle(Jedis conn, String user, String title, String link) {
String articleId = String.valueOf(conn.incr("article:")); String voted = "voted:" + articleId;
conn.sadd(voted, user);
conn.expire(voted, ONE_WEEK_IN_SECONDS); long now = System.currentTimeMillis() / 1000;
String article = "article:" + articleId;
HashMap<String,String> articleData = new HashMap<String,String>();
articleData.put("title", title);
articleData.put("link", link);
articleData.put("user", user);
articleData.put("now", String.valueOf(now));
articleData.put("votes", "1");
conn.hmset(article, articleData);
conn.zadd("score:", now + VOTE_SCORE, article);
conn.zadd("time:", now, article); return articleId;
} public void articleVote(Jedis conn, String user, String article) {
long cutoff = (System.currentTimeMillis() / 1000) - ONE_WEEK_IN_SECONDS;
if (conn.zscore("time:", article) < cutoff){
return;
} String articleId = article.substring(article.indexOf(':') + 1);
if (conn.sadd("voted:" + articleId, user) == 1) {
conn.zincrby("score:", VOTE_SCORE, article);
conn.hincrBy(article, "votes", 1);
}
} public List<Map<String,String>> getArticles(Jedis conn, int page) {
return getArticles(conn, page, "score:");
} public List<Map<String,String>> getArticles(Jedis conn, int page, String order) {
int start = (page - 1) * ARTICLES_PER_PAGE;
int end = start + ARTICLES_PER_PAGE - 1; Set<String> ids = conn.zrevrange(order, start, end);
List<Map<String,String>> articles = new ArrayList<Map<String,String>>();
for (String id : ids){
Map<String,String> articleData = conn.hgetAll(id);
articleData.put("id", id);
articles.add(articleData);
} return articles;
} public void addGroups(Jedis conn, String articleId, String[] toAdd) {
String article = "article:" + articleId;
for (String group : toAdd) {
conn.sadd("group:" + group, article);
}
} public List<Map<String,String>> getGroupArticles(Jedis conn, String group, int page) {
return getGroupArticles(conn, group, page, "score:");
} public List<Map<String,String>> getGroupArticles(Jedis conn, String group, int page, String order) {
String key = order + group;
if (!conn.exists(key)) {
ZParams params = new ZParams().aggregate(ZParams.Aggregate.MAX);
conn.zinterstore(key, params, "group:" + group, order);
conn.expire(key, 60);
}
return getArticles(conn, page, key);
} private void printArticles(List<Map<String,String>> articles){
for (Map<String,String> article : articles){
System.out.println(" id: " + article.get("id"));
for (Map.Entry<String,String> entry : article.entrySet()){
if (entry.getKey().equals("id")){
continue;
}
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
}
}
}

package redis.inaction;
import redis.clients.jedis.Jedis;import redis.clients.jedis.ZParams;
import java.util.*;
public class Chapter01 {    private static final int ONE_WEEK_IN_SECONDS = 7 * 86400;    private static final int VOTE_SCORE = 432;    private static final int ARTICLES_PER_PAGE = 25;
    public static final void main(String[] args) {        new Chapter01().run();    }
    public void run() {        Jedis conn = new Jedis("192.168.7.146",6379);        conn.select(15);        conn.flushAll();        String articleId = postArticle(            conn, "username", "A title", "http://www.google.com");        System.out.println("We posted a new article with id: " + articleId);        System.out.println("Its HASH looks like:");        Map<String,String> articleData = conn.hgetAll("article:" + articleId);        for (Map.Entry<String,String> entry : articleData.entrySet()){            System.out.println("  " + entry.getKey() + ": " + entry.getValue());        }
        System.out.println();
        articleVote(conn, "other_user", "article:" + articleId);        String votes = conn.hget("article:" + articleId, "votes");        System.out.println("We voted for the article, it now has votes: " + votes);        assert Integer.parseInt(votes) > 1;
        System.out.println("The currently highest-scoring articles are:");        List<Map<String,String>> articles = getArticles(conn, 1);        printArticles(articles);        assert articles.size() >= 1;
        addGroups(conn, articleId, new String[]{"new-group"});        System.out.println("We added the article to a new group, other articles include:");        articles = getGroupArticles(conn, "new-group", 1);        printArticles(articles);        assert articles.size() >= 1;    }
    public String postArticle(Jedis conn, String user, String title, String link) {        String articleId = String.valueOf(conn.incr("article:"));
        String voted = "voted:" + articleId;        conn.sadd(voted, user);        conn.expire(voted, ONE_WEEK_IN_SECONDS);
        long now = System.currentTimeMillis() / 1000;        String article = "article:" + articleId;        HashMap<String,String> articleData = new HashMap<String,String>();        articleData.put("title", title);        articleData.put("link", link);        articleData.put("user", user);        articleData.put("now", String.valueOf(now));        articleData.put("votes", "1");        conn.hmset(article, articleData);        conn.zadd("score:", now + VOTE_SCORE, article);        conn.zadd("time:", now, article);
        return articleId;    }
    public void articleVote(Jedis conn, String user, String article) {        long cutoff = (System.currentTimeMillis() / 1000) - ONE_WEEK_IN_SECONDS;        if (conn.zscore("time:", article) < cutoff){            return;        }
        String articleId = article.substring(article.indexOf(':') + 1);        if (conn.sadd("voted:" + articleId, user) == 1) {            conn.zincrby("score:", VOTE_SCORE, article);            conn.hincrBy(article, "votes", 1);        }    }

public List<Map<String,String>> getArticles(Jedis conn, int page) {        return getArticles(conn, page, "score:");    }
    public List<Map<String,String>> getArticles(Jedis conn, int page, String order) {         int start = (page - 1) * ARTICLES_PER_PAGE;        int end = start + ARTICLES_PER_PAGE - 1;
        Set<String> ids = conn.zrevrange(order, start, end);        List<Map<String,String>> articles = new ArrayList<Map<String,String>>();        for (String id : ids){            Map<String,String> articleData = conn.hgetAll(id);            articleData.put("id", id);            articles.add(articleData);        }
        return articles;    }
    public void addGroups(Jedis conn, String articleId, String[] toAdd) {        String article = "article:" + articleId;        for (String group : toAdd) {            conn.sadd("group:" + group, article);        }    }
    public List<Map<String,String>> getGroupArticles(Jedis conn, String group, int page) {        return getGroupArticles(conn, group, page, "score:");    }
    public List<Map<String,String>> getGroupArticles(Jedis conn, String group, int page, String order) {        String key = order + group;        if (!conn.exists(key)) {            ZParams params = new ZParams().aggregate(ZParams.Aggregate.MAX);            conn.zinterstore(key, params, "group:" + group, order);            conn.expire(key, 60);        }        return getArticles(conn, page, key);    }
    private void printArticles(List<Map<String,String>> articles){        for (Map<String,String> article : articles){            System.out.println("  id: " + article.get("id"));            for (Map.Entry<String,String> entry : article.entrySet()){                if (entry.getKey().equals("id")){                    continue;                }                System.out.println("    " + entry.getKey() + ": " + entry.getValue());            }        }    }}

redis-投票的更多相关文章

  1. redis投票计数

    <?php /** * * 缓存利用测试,这里我们获取传过来的投票数据,每次加1,如果增加到了设定值,才将投票 * 次数写回mysql,这大大减轻了与mysql链接的开销,redis的使用由此可 ...

  2. Redis笔记5-redis高可用方案

    一.哨兵机制 有了主从复制的实现以后,如果想对主服务器进行监控,那么在redis2.6以后提供了一个"哨兵"的机制.顾名思义,哨兵的含义就是监控redis系统的运行状态.可以启动多 ...

  3. redis备忘录

    Redis 是一个基于内存的高性能key-value数据库.Redis本质上是一个Key-Value类型的内存数据库,很像memcached,整个数据库统统加载在内存当中进行操作,定期通过异步操作把数 ...

  4. Redis in Action 文章投票

    原书用 Python 与 Redis 进行交互,我用 PHP 来实现. 环境:LNMP(CentOS 6.6 + Nginx 1.8.0 + MySQL 5.6.23 + PHP 5.6.9)+ Re ...

  5. php+redis 简易的实现文章发布系统(用户投票系统)

    /** * @data 文章发布 * 文章详情散列表中递增ID,讲文章发布者ID写入投票用户集合中,设置投票时间为一周 * 讲文章内容写入文章散列中,讲文章写入文章评分有序集合和文章发布有序集合中 * ...

  6. redis 实例2 构建文章投票网站后端

    redis 实例2 构建文章投票网站后端   1.限制条件 一.如果网站获得200张支持票,那么这篇文章被设置成有趣的文章 二.如果网站发布的文章中有一定数量被认定为有趣的文章,那么这些文章需要被设置 ...

  7. 使用redis构建文章投票系统

    首先,我得说明这篇博客基本上就是<<redis in action>>第一章内容的读书笔记. 需求 首先,说明一下,我们的需求 用户可以发表文章,发表时,自己就默认的给自己的文 ...

  8. Redis实现文章投票功能

    Redis的具体操作这里就不说了,说一下需求和设计思路. 需求:自己实现一个文章投票的功能1.能够按照时间分页倒叙查看文章信息2.能够给文章投票,一个用户给一篇文章只能投票一次3.需要记录分值.每次投 ...

  9. php与Redis实现一个100万用户的投票项目,如何实现实时查看投票情况?

    好了,什么是冷热数据交换呢? 很土的解释一下,冷数据就是之前使用的数据,有种过去式的感觉,而热数据就是当前的数据,理解为现在进行时吧.如何交换呢?就是将Redis的数据周期存储到mysql中! 整体的 ...

  10. php结合Redis实现100万用户投票项目,并实时查看到投票情况的案例

    场景:某网站需要对其项目做一个投票系统,投票项目上线后一小时之内预计有100万用户进行投票,希望用户投票完就能看到实时的投票情况 这个场景可以使用redis+mysql冷热数据交换来解决. 何为冷热数 ...

随机推荐

  1. JQuery事件(2)

    jQuery 事件 下面是 jQuery 中事件方法的一些例子: Event 函数 绑定函数至 $(document).ready(function) 将函数绑定到文档的就绪事件(当文档完成加载时) ...

  2. [转自SA]浅谈nginx的工作原理和使用

    nginx apache 简单对比 nginx 相对 apache 的优点: 轻量级,同样起web 服务,比apache 占用更少的内存及资源 抗并发,nginx 处理请求是异步非阻塞的,而 apac ...

  3. 第96:SVM简介与简单应用

    详细推到见:https://blog.csdn.net/v_july_v/article/details/7624837 python实现方式:

  4. 架构师成长之路5.4-Saltstack配置管理(LAMP架构案例)

    点击架构师成长之路 架构师成长之路5.4-Saltstack配置管理(LAMP架构案例) 配置管理工具: Pupper:1. 采用ruby编程语言:2. 安装环境相对较复杂:3.不支持远程执行,需要F ...

  5. 自学Python5.7-面向对象三大基本特征_封装

    自学Python之路-Python基础+模块+面向对象自学Python之路-Python网络编程自学Python之路-Python并发编程+数据库+前端自学Python之路-django 自学Pyth ...

  6. android studio 下载sdk

    一.打开android studio 的"setting",搜索 "proxy",选中"No Proxy"

  7. BZOJ 3876 统一下界上下界费用流

    //Mcmf LargeDumpling #include<iostream> #include<cstdio> #include<cstdlib> #includ ...

  8. java调用js函数

    问题:js函数可能有多个,之间有相互调用关系,有jquery jar包 org.mozilla.javascript-1.7.2 js   envjs-1.2.js java代码 import jav ...

  9. Linux下Discuz!7.2 LAMP环境搭建

    linux下Discuz LAMP环境搭建 1.需要的源代码 httpd-2.2.15.tar.gz          mysql-5.1.44.tar.gz     php-5.3.2.tar.gz ...

  10. sklearn学习一

    转发说明:by majunman    from HIT    email:2192483210@qq.com 简介:scikit-learn是数据挖掘和数据分析的有效工具,它建立在 NumPy, S ...