redis學習筆記---java操做redis,使用expire模擬指定時間段內限制ip訪問的次數;

        首先加入maven依賴,使用JUinit作單元測試。 java

        

<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);
	}
}
相關文章
相關標籤/搜索