2019版:第五章:Redis 的Java客户端 Jedis

一、测试连通性

  1、Jedis 所需要的 jar包,可通过 Maven 的依赖引入

  2、连接虚拟机中的Redis注意事项

禁用Linux的防火墙:Linux(CentOS7)里执行命令 : systemctl stop firewalld.service
redis.conf中注释掉bind 127.0.0.1 ,然后 protect-mode no

  

  3、Jedis 测试连通性

public class RedisTest {

    @Test
    public void test() {
        //连接本地的 Redis 服务
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        //查看服务是否运行,打出pong表示OK
        System.out.println(jedis.ping());

        jedis.set("name", "张三");
        String name = jedis.get("name");
        System.out.println("name = " + name);

        jedis.close();
    }
}

二、常用 API

  1、操作 key

    private Jedis jedis = null;

    @Before
    public void getJedis() {
        jedis = new Jedis("127.0.0.1", 6379);
    }

    @Test
    public void testKey() {
        Set<String> keys = jedis.keys("*");
        Iterator<String> iterator = keys.iterator();
        for(; iterator.hasNext();) {
            String key = iterator.next();
            System.out.println("key = " + key);
        }

        System.out.println("jedis.exists====>" + jedis.exists("k2"));
        System.out.println(jedis.ttl("k1"));
    }

  2、操作 String

    @Test
    public void testString() {
        System.out.println(jedis.get("k1"));

        jedis.set("k3", "k3_Redis");
        System.out.println("----------");
        jedis.mset("k5", "v5", "k6", "v6", "k7", "v7");
        System.out.println(jedis.mget("k5", "k6", "k7"));
    }

  3、操作 List

    @Test
    public void testList() {
        jedis.lpush("myList", "a");
        jedis.lpush("myList", "b");
        jedis.lpush("myList", "c");
        jedis.lpush("myList", "d");

        List<String> myList = jedis.lrange("myList", 0, -1);
        for (String s : myList) {
            System.out.println("s = " + s);
        }
    }

  4、操作 Set

    @Test
    public void testSet() {
        jedis.sadd("mySet", "jd001");
        jedis.sadd("mySet", "jd002");
        jedis.sadd("mySet", "jd003");
        jedis.sadd("mySet", "jd004");
        jedis.sadd("mySet", "jd001");

        Set<String> mySet = jedis.smembers("mySet");
        for (String s : mySet) {
            System.out.println("s = " + s);
        }
    }

  5、操作 Hash

    @Test
    public void testHash() {
        jedis.hset("myHash", "username", "lisi");
        System.out.println(jedis.hget("myHash", "username"));

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sex", "男");
        map.put("age", "25");
        map.put("email", "ls@126.com");

        jedis.hmset("myHash2", map);
        List<String> result = jedis.hmget("myHash2", "sex", "age", "email");
        for (String s : result) {
            System.out.println("s = " + s);
        }
    }

  6、操作 ZSet

    @Test
    public void testZSet() {
        jedis.zadd("zSet", 40d, "v1");
        jedis.zadd("zSet", 60d, "v2");
        jedis.zadd("zSet", 80d, "v3");
        jedis.zadd("zSet", 90d, "v4");

        Set<String> zSet = jedis.zrange("zSet", 0, -1);
        Iterator<String> iterator = zSet.iterator();
        for(; iterator.hasNext();) {
            System.out.println(iterator.next());
        }
    }

三、验证码案例

  完成一个手机验证码功能

  要求:

  1)输入手机号,点击发送后随机生成6位数字码,2分钟有效

  2)输入验证码,点击验证,返回成功或失败

  3)每个手机号每天只能输入3次

   工具类:

public class JedisPoolUtil {

    private static volatile JedisPool jedisPool = null;

    private JedisPoolUtil(){}

    public static JedisPool getJedisPoolInstance() {
        if (null == jedisPool) {
            synchronized (JedisPoolUtil.class) {
                if (null == jedisPool) {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(1000);
                    poolConfig.setMaxIdle(32);
                    poolConfig.setMaxWaitMillis(100 * 1000);
                    poolConfig.setTestOnBorrow(true);

                    jedisPool = new JedisPool(poolConfig, "127.0.0.1", 6379);
                }
            }
        }
        return jedisPool;
    }

    public static void release(JedisPool jedisPool, Jedis jedis) {
        if (null != jedis) {
            jedisPool.returnResourceObject(jedis);
        }
    }
}

  发送验证码:

@WebServlet(value = "/codeSenderServlet")
public class CodeSenderServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取参数
        String phoneNo = req.getParameter("phone_no");

        //生成验证码
        String code = getCode(6);

        //拼接 key
        String codeKey = "VerifyCode:" + phoneNo + ":code"; //VerifyCode:12345:code
        String countKey = "VerifyCode:" + phoneNo + ":count";

        JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis = jedisPool.getResource();
        
        //判断发送验证码的次数
        String count = jedis.get(countKey);
        if (count == null) {
            //还没有发送过,代表第一次
            jedis.setex(countKey, 24*60*60, "1");
        } else if (Integer.parseInt(count) <= 2) {
            jedis.incr(countKey);
        } else if (Integer.parseInt(count) > 2){
            resp.getWriter().print("limit");
            JedisPoolUtil.release(jedisPool, jedis);
            return ;
        }

        //向redis中进行存储,以手机号为键,以验证码为值
        jedis.setex(codeKey, 24 * 60 * 60, code);
        JedisPoolUtil.release(jedisPool, jedis);
        resp.getWriter().print(true);
    }

    private String getCode(int length) {
        String code = "";
        Random random = new Random();
        for(int i = 0; i < length; i++) {
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;
    }
}

  校验验证码:

@WebServlet(value = "/codeVerifyServlet")
public class CodeVerifyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取验证码和手机号
        String phoneNo = req.getParameter("phone_no");
        String verifyCode = req.getParameter("verify_code");

        //拼接key
        String codeKey = "VerifyCode:" + phoneNo + ":code";
        //从redis中获取手机号所对应的验证码
        JedisPool jedisPool = JedisPoolUtil.getJedisPoolInstance();
        Jedis jedis = jedisPool.getResource();

        String code = jedis.get(codeKey);
        if(verifyCode.equals(code)) {
            resp.getWriter().print(true);
        }
        JedisPoolUtil.release(jedisPool, jedis);
    }
}

  页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <%
        String ctx = request.getContextPath();
    %>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <script  src="${pageContext.request.contextPath}/static/jquery/jquery-3.1.0.js"></script>
    <link href="<%=request.getContextPath()%>/static/bs/css/bootstrap.min.css" rel="stylesheet" />
    <script  src="<%=request.getContextPath()%>/static/bs/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">
    <div class="row">
        <div id="alertdiv" class="col-md-12">
            <form class="navbar-form navbar-left" role="search" id="codeform">
                <div class="form-group">
                    <input type="text" class="form-control" placeholder="填写手机号" name="phone_no">
                    <button type="button" class="btn btn-default" id="sendCode">发送验证码</button><br>
                    <font id="countdown" color="red" ></font>
                    <br>
                    <input type="text" class="form-control" placeholder="填写验证码" name="verify_code">
                    <button type="button" class="btn btn-default" id="verifyCode">确定</button>
                    <font id="result" color="green" ></font><font id="error" color="red" ></font>
                </div>
            </form>
        </div>
    </div>
</div>

</body>
<script type="text/javascript">
    var t=120;//设定倒计时的时间
    var interval;
    function refer(){
        $("#countdown").text("请于"+t+"秒内填写验证码 "); // 显示倒计时
        t--; // 计数器递减
        if(t<=0){
            clearInterval(interval);
            $("#countdown").text("验证码已失效,请重新发送! ");
        }
    }

    $(function(){
        $("#sendCode").click( function () {

            $.post("${pageContext.request.contextPath}/codeSenderServlet", $("#codeform").serialize(), function(data){
                if(data=="true"){
                    t=120;
                    clearInterval(interval);
                    interval= setInterval("refer()", 1000);//启动1秒定时
                }else if (data=="limit"){
                    clearInterval(interval);
                    $("#countdown").text("单日发送超过次数! ")
                }
            });
        });

        $("#verifyCode").click( function () {

            $.post("${pageContext.request.contextPath}/codeVerifyServlet", $("#codeform").serialize(), function(data){
                if(data=="true"){
                    $("#result").attr("color","green");
                    $("#result").text("验证成功");
                    clearInterval(interval);
                    $("#countdown").text("");
                }else{
                    $("#result").attr("color","red");
                    $("#result").text("验证失败");
                }
            });
        });


    });
</script>
</html>

 

原文地址:https://www.cnblogs.com/niujifei/p/15793420.html