Redis学习---Java应用Redis Jedis
阅读目录
1. 封装 RedisUtil 构建 redis 连接池
2. 使用 Junit Test Redis String,List,Set Hash 等基本数据类型存储
3.Redis 事务以及管道应用
4.Redis 限制登录小应用
< 一 > 封装 RedisUtil 构建 redis 连接池
1. Redis 提供各种语言的 API,目前基于 Java 语言实现的封装 Jar 有 Jedis, 在 maven 版本库最新版本 2.9.0 版本
使用 maven 构建工程,配置 pom.xml 文件,即可下载 jedis Jar
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2. 封装 RedisUtil. 初始化连接池,使用 static 模块初始化,即类加载时就初始化
private static String HOST = "192.168.110.210"; private static Integer PORT = 6379; private static String AUTH = "123456"; // 可用连接实例的最大数目,默认值为 8; // 如果赋值为 -1,则表示不限制;如果 pool 已经分配了 maxActive 个 jedis 实例,则此时 pool 的状态为 exhausted(耗尽)。 private static int MAX_ACTIVE = 1024; // 控制一个 pool 最多有多少个状态为 idle(空闲的) 的 jedis 实例,默认值也是 8. private static int MAX_IDLE = 200; // 等待可用连接的最大时间,单位毫秒,默认值为 -1,表示永不超时。如果超过等待时间,则直接抛出 private static int MAX_WAIT = 10000; private static int TIMEOUT = 10000; // 在 borrow 一个 jedis 实例时,是否提前进行 validate 操作;如果为 true,则得到的 jedis 实例均是可用的; private static boolean TEST_ON_BORROW = true; private static JedisPool jedisPool = null;</span><span style="color: rgba(0, 0, 255, 1)">static</span><span style="color: rgba(0, 0, 0, 1)"> { </span><span style="color: rgba(0, 0, 255, 1)">try</span><span style="color: rgba(0, 0, 0, 1)"> { JedisPoolConfig jedisPoolConfig </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> JedisPoolConfig(); jedisPoolConfig.setMaxIdle(MAX_IDLE); jedisPoolConfig.setMaxWaitMillis(MAX_WAIT); jedisPoolConfig.setMaxTotal(MAX_ACTIVE); jedisPoolConfig.setTestOnBorrow(TEST_ON_BORROW); jedisPool </span>= <span style="color: rgba(0, 0, 255, 1)">new</span><span style="color: rgba(0, 0, 0, 1)"> JedisPool(jedisPoolConfig, HOST, PORT, TIMEOUT, AUTH); } </span><span style="color: rgba(0, 0, 255, 1)">catch</span><span style="color: rgba(0, 0, 0, 1)"> (Exception ex) { System.out.println(</span>"===初始化redis连接池出错==="<span style="color: rgba(0, 0, 0, 1)">); } }</span></pre>
3. 实例化 Jedis 对象, 获得 redis 服务器连接池的一个客户端连接
public static synchronized Jedis getJedis() { Jedis jedis = null; if (jedisPool != null) { jedis = jedisPool.getResource(); System.out.println("jedis===="+jedis);} return jedis; }
< 二 > Redis 基本数据类型应用
1,String 类型应用
@Test public void testString() { jedis.set("name", "JJ");// 向 key --->name 放入了 value--->JJ System.out.println("name value is" + jedis.get("name")); // 拼接 jedis.append("name", "is da jj"); System.out.println("name value is"+ jedis.get("name")); // 删除 jedis.del("name"); System.out.println("name value is" + jedis.get("name")); //设置多个 key-value jedis.mset("name", "周哥", "age", "27", "sex", "男"); //对某个 Key 进行加 1 操作 jedis.incr("age"); //只允许对 int 类型操作 System.out.println(jedis.get("name") + "-" + jedis.get("age") + "-" + jedis.get("sex"));}
2. 操作 Hash 类型,Map
public void testMap() { Map<String, String> map = new HashMap<String, String>(); map.put("name", "梅西"); map.put("age", "30"); map.put("sex", "男"); // 设置 key 为 user value 为 map 操作 jedis.hmset("user", map); List<String> list = jedis.hmget("user", "name", "age", "sex"); System.out.println("list" + list);Iterator<String> iterator = jedis.hkeys("user").iterator(); while (iterator.hasNext()) { String key = iterator.next(); System.out.println("key=" + key + jedis.hmget("user", key));} }</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 删除map某个key</span> jedis.hdel("user", "name"<span style="color: rgba(0, 0, 0, 1)">); System.out.println(jedis.hmget(</span>"user", "name"<span style="color: rgba(0, 0, 0, 1)">)); System.out.println(jedis.hlen(</span>"user"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 返回key为“user”的键中存放的值个数</span> System.out.println(jedis.exists("user"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 查找是否“user” key的是否存在</span> System.out.println(jedis.hkeys("user")); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 返回所有的”user“ key 的map所有的key</span> System.out.println(jedis.hvals("user")); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 返回“user” key的所有值</span>
3. 操作 List
public void testList() {jedis.del(</span>"java framework"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 取key 为java framework的所有内容</span> System.out.println(jedis.lrange("java framework", 0, -1<span style="color: rgba(0, 0, 0, 1)">)); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 倒序放入</span> jedis.lpush("java framework", "spring"<span style="color: rgba(0, 0, 0, 1)">); jedis.lpush(</span>"java framework", "struct"<span style="color: rgba(0, 0, 0, 1)">); jedis.lpush(</span>"java framework", "hibernate"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有</span> System.out.println(jedis.lrange("java framework", 0, -1<span style="color: rgba(0, 0, 0, 1)">)); jedis.del(</span>"java framework"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 顺序放入</span> jedis.rpush("java framework", "spring"<span style="color: rgba(0, 0, 0, 1)">); jedis.rpush(</span>"java framework", "struts"<span style="color: rgba(0, 0, 0, 1)">); jedis.rpush(</span>"java framework", "hibernate"<span style="color: rgba(0, 0, 0, 1)">); System.out.println(jedis.lrange(</span>"java framework", 0, -1<span style="color: rgba(0, 0, 0, 1)">)); }</span></pre>
4. 操作 Set
public void testSet() { // 添加 jedis.sadd("user2", "liuling"); jedis.sadd("user2", "xinxin"); jedis.sadd("user2", "ling"); jedis.sadd("user2", "zhangxinxin"); jedis.sadd("user2", "who"); // 移除 noname jedis.srem("user2", "who"); System.out.println(jedis.smembers("user2"));// 获取所有加入的 value System.out.println(jedis.sismember("user2", "who"));// 判断 who // 是否是 user 集合的元素 System.out.println(jedis.srandmember("user2"));// 返回 key user2 随机的一个元素 System.out.println(jedis.scard("user2"));// 返回集合的元素个数 }
< 三 > Redis 事务以及管道应用
1. 事务操作
public void testTranstaction() { jedis.del("n=0"); Transaction tx = jedis.multi(); // 开启事务 for (int i = 0; i < 10000; i++) { tx.set("n=" + i, "n=" + i); // 注意使用事务 set }tx.zadd(</span>"foo", 1, "a"<span style="color: rgba(0, 0, 0, 1)">); tx.zadd(</span>"foo", 2, "b"<span style="color: rgba(0, 0, 0, 1)">); tx.zadd(</span>"foo", 3, "c"<span style="color: rgba(0, 0, 0, 1)">); Response</span><Set<String>> sose = tx.zrange("foo", 0, -1<span style="color: rgba(0, 0, 0, 1)">); tx.exec();</span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 提交事务 </span><span style="color: rgba(0, 128, 0, 1)">//
System.out.println(jedis.get("n=0"));
System.out.println(sose.get());
jedis.disconnect();
}
2. 管道方式操作
public void testPipelined() throws Exception {Response<Set<String>> stResponse2 = pipeline.zrange("foottt", 0, -1);Pipeline pipeline </span>=<span style="color: rgba(0, 0, 0, 1)"> jedis.pipelined(); pipeline.zadd(</span>"foottt", 0, "aa"<span style="color: rgba(0, 0, 0, 1)">); pipeline.zadd(</span>"foottt", 1, "ba"<span style="color: rgba(0, 0, 0, 1)">); pipeline.zadd(</span>"foottt", 2, "ca"<span style="color: rgba(0, 0, 0, 1)">); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">注意存入的</span>
pipeline.sync(); System.out.println(stResponse2.get().size()); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> Response<Set<String>> sose2 = pipeline.zrange("foo", 0, -1); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> System.out.println(sose2.get());</span><span style="color: rgba(0, 0, 0, 1)"> }</span></pre>
redis 管道的方式可以减少客户端与 redis 的通信次数,提高性能
< 四 > 使用 redis,限制每个用户的 ID 一个小时内只能登陆 5 次
实现思路:记录用户第五次的登陆时间,与现在的时间之差是否已经大于 1 小时, 如果大于则可以登陆,如果不大于则不能登陆
public void testLogin4Hour() throws Exception { String id = "1234567"; /* * jedis.rpush(id, String.valueOf(System.currentTimeMillis())); * jedis.rpush(id,"操"); System.out.println(jedis.lindex(id, 1)); // * 取出 key 为 id 的第 2 个元素值 */ jedis.del(id); // 模拟用户 5 次登陆 for (int i = 0; i < 5; i++) {jedis.rpush(id, String.valueOf(System.currentTimeMillis())); System.out.println(</span>"第" + (i + 1) + "次登陆的时间:" + DateUtils.date2string(<span style="color: rgba(0, 0, 255, 1)">new</span> Date(System.currentTimeMillis()), "YYYY-MM-dd HH🇲🇲ss"<span style="color: rgba(0, 0, 0, 1)">)); </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 每隔10分钟登陆一次,第5次登陆则在40分钟之后</span> Thread.sleep(12 * 60 * 1000<span style="color: rgba(0, 0, 0, 1)">); } </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)"> 取出第五次的登陆的时间点</span> String value_5 = jedis.lindex(id, 4<span style="color: rgba(0, 0, 0, 1)">); System.out.println(</span>"第5次登陆的时间:" + DateUtils.date2string(<span style="color: rgba(0, 0, 255, 1)">new</span> Date(Long.valueOf(value_5)), "YYYY-MM-dd HH🇲🇲ss"<span style="color: rgba(0, 0, 0, 1)">)); Long diffTime </span>= System.currentTimeMillis() -<span style="color: rgba(0, 0, 0, 1)"> Long.valueOf(value_5); </span><span style="color: rgba(0, 0, 255, 1)">if</span> (value_5 != <span style="color: rgba(0, 0, 255, 1)">null</span> && diffTime <= 1 * 60 * 60 * 1000<span style="color: rgba(0, 0, 0, 1)">) { System.out.println(</span>"不能登陆"<span style="color: rgba(0, 0, 0, 1)">); } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> { System.out.println(</span>"可以继续登陆"<span style="color: rgba(0, 0, 0, 1)">); } jedis.disconnect(); }</span></pre>