您的位置:首页 > 数据库 > Redis

redis学习笔记---java操作redis,使用expire模拟指定时间段内限制ip访问的次数;

2015-12-14 00:00 861 查看
摘要: 本系列redis博客纯属个人学习总结记录之用,初学者,如若见不当之处,望指教。本篇使用java操作redis,使用expire实现了一个简单模拟限制ip访问次数,下面附带了一个管道和普通方式插入1万条数据所耗时间的对比

首先加入maven依赖,使用JUinit做单元测试。

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.0</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>


redisutil类,创建一个线程池,可以返回redis连接资源以及释放资源

/**
* redis工具类,从redis链接池中获取一个链接资源
* @author Hades
* time:2015年12月14日
*/
public class RedisUtils {
//定义连接池
public static JedisPool pool = null;
/**
* 获取链接资源
* @return
*/
public static synchronized Jedis getJedis() {
if(pool==null){
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(100);//最大连接数
jedisPoolConfig.setMaxIdle(10);
jedisPoolConfig.setMaxWaitMillis(1000);//类似于超时时间
jedisPoolConfig.setTestOnBorrow(true);
pool = new JedisPool(jedisPoolConfig,"192.168.57.133",6379);//创建连接池
}

Jedis jedis = pool.getResource();
return jedis;
}
/**
* 释放链接资源
* @param jedis
*/
public static void returnJedis(Jedis jedis) {
pool.returnResourceObject(jedis);
}


redis客户端类,使用的是juinit做单元测试哈

/**
* redis测试类
* @author Hades
*
*/
public class RedisTest {
static Jedis jedis =RedisUtils.getJedis();
@Test
public void test3() throws Exception {
String ip ="192.168.57.2";//访问的ip
//测试
for (int i = 0; i < 20; i++) {
boolean flag = testLogin(ip);
System.out.println(flag);
}
}
/**
* 模拟限制ip指定时间段内访问次数
* @param ip
* @return
*/
public boolean testLogin(String ip) {
String value = jedis.get(ip);
if(value==null){
jedis.set(ip, "1");
jedis.expire(ip, 60);//设置过期时间60秒
return true;
}else{
int parseInt = Integer.parseInt(value);
//60秒内访问超过10次,就禁止访问
if(parseInt>10){
System.out.println("访问受限!!!!");
return false;
}

jedis.incr(ip);
}

return true;
}

/**
* 不使用管道 向jedis插入一万条数据消耗时间:3184
*/
@Test
public void test2() throws Exception{
// TODO Auto-generated method stub
long start = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
jedis.set("a"+i, i+"");
jedis.expire("a"+i, 60);
}

System.out.println(System.currentTimeMillis()-start);
}
/**
* 使用管道命令批量导入数据 所需时间:204
* @throws Exception
*/
@Test
public void test4() throws Exception {
long start = System.currentTimeMillis();
Pipeline pipelined = jedis.pipelined();
for (int i = 0; i < 10000; i++) {
pipelined.set("a"+i, i+"");
pipelined.expire("a"+i, 60);
}
pipelined.sync();
System.out.println(System.currentTimeMillis()-start);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息