Redis入门——Java接口

1、 maven配置

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

2、 Java操作Redis数据接口

package com.coshaho.learn.redis;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import redis.clients.jedis.Jedis;

/**
 * 
 * MyRedisLearn.java Create on 2017年11月4日 下午4:40:39    
 *    
 * 类功能说明:  Redis Java接口测试 
 *
 * Copyright: Copyright(c) 2013 
 * Company: COSHAHO
 * @Version 1.0
 * @Author coshaho
 */
public class MyRedisLearn 
{
    private Jedis jedis; 
    
    public static void main(String[] args)
    {
        MyRedisLearn redis = new MyRedisLearn();
        redis.init();
        redis.testString();
        redis.testMap();
        redis.testList();
        redis.testSet();
    }
    
    public void init() 
    {
        jedis = new Jedis("127.0.0.1", 6379);
        jedis.auth("coshaho");  
    }
    
    public void testString() 
    {
        // 设置值
        jedis.del("string1");
        jedis.set("string1","coshaho"); 
        System.out.println(jedis.get("string1"));
        
        // 字符串拼接
        jedis.append("string1", " is my name"); //拼接
        System.out.println(jedis.get("string1")); 
        
        // 删除字符串
        jedis.del("string1");
        System.out.println(jedis.get("string1"));
        
        // 设置多个键值对
        jedis.del("name");
        jedis.del("age");
        jedis.mset("name","coshaho","age","28");
        // 加1操作
        jedis.incr("age");
        System.out.println(jedis.get("name") + "-" + jedis.get("age"));
    }
    
    public void testMap() 
    {
        jedis.del("user");
        Map<String, String> map = new HashMap<String, String>();
        map.put("name", "coshaho");
        map.put("age", "28");
        map.put("sex", "male");
        jedis.hmset("user",map);
        
        // 参数1 key 参数2 filed 参数3 field
        List<String> rsmap = jedis.hmget("user", "name", "age", "sex");
        System.out.println(rsmap);  
  
        // 删除map中的某个键值  
        jedis.hdel("user","age");
        System.out.println(jedis.hmget("user", "age"));   
        System.out.println(jedis.hlen("user"));  
        System.out.println(jedis.exists("user"));
        System.out.println(jedis.hkeys("user"));
        System.out.println(jedis.hvals("user"));
  
        Iterator<String> iter=jedis.hkeys("user").iterator();  
        while (iter.hasNext())
        {  
            String key = iter.next();  
            System.out.println(key+":"+jedis.hmget("user",key));  
        }  
    }
    
    public void testList()
    {  
        // 删除list
        jedis.del("language");  
        System.out.println(jedis.lrange("language",0,-1));  
        
        jedis.lpush("language","english");  
        jedis.lpush("language","chinese");  
        jedis.lpush("language","japanese");  
        
        // 第一个是key,第二个是起始位置,第三个是结束位置,jedis.llen获取长度 -1表示取得所有  
        System.out.println(jedis.lrange("language",0,-1));  
        
        jedis.del("language");
        jedis.rpush("language","java");  
        jedis.rpush("language","c");  
        jedis.rpush("language","python"); 
        System.out.println(jedis.lrange("language",0,-1));
        
        // 双向列表,jedis 排序 
        jedis.del("a");
        jedis.rpush("a", "1");  
        jedis.lpush("a","6");  
        jedis.lpush("a","3");  
        jedis.lpush("a","9");  
        System.out.println(jedis.lrange("a",0,-1));
        System.out.println(jedis.sort("a")); 
        System.out.println(jedis.lrange("a",0,-1));  
    }  
    
    public void testSet()
    {  
        jedis.del("b");  
        jedis.sadd("b","张三");  
        jedis.sadd("b","李四");  
        jedis.sadd("b","王五");  
        jedis.sadd("b","胜七");
        jedis.sadd("b","段九");  
        
        // 移除
        jedis.srem("b","胜七");  
        System.out.println(jedis.smembers("b"));  
        System.out.println(jedis.sismember("b", "胜七"));  
        System.out.println(jedis.srandmember("b"));  
        System.out.println(jedis.scard("b"));
    }  
}

3、 Java创建Redis连接池

 

package com.coshaho.learn.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public final class RedisPool 
{
    //Redis服务器IP
    private static String ADDR = "127.0.0.1";
    
    //Redis的端口号
    private static int PORT = 6379;
    
    //访问密码
    private static String AUTH = "coshaho";
    
    //可用连接实例的最大数目,默认值为8;
    //如果赋值为-1,则表示不限制;如果pool已经分配了MAX_TOTAL个jedis实例,则此时pool的状态为exhausted(耗尽)。
    private static int MAX_TOTAL = 1024;
    
    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
    private static int MAX_IDLE = 200;
    
    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
    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;
    
    /**
     * 初始化Redis连接池
     */
    static 
    {
        try 
        {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxIdle(MAX_IDLE);
            config.setTestOnBorrow(TEST_ON_BORROW);
            config.setMaxTotal(MAX_TOTAL);
            config.setMaxWaitMillis(MAX_WAIT);
            jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }
    
    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() 
    {
        try 
        {
            if (jedisPool != null) 
            {
                Jedis resource = jedisPool.getResource();
                return resource;
            } 
            else 
            {
                return null;
            }
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void close(final Jedis jedis) 
    {
        if (jedis != null) {
            jedis.close();;
        }
    }
    
    public static void main(String[] args)
    {
        RedisPool.getJedis().set("pool", "连接池");
        System.out.println(RedisPool.getJedis().get("pool"));
    }
}

 

posted @ 2017-11-04 16:26  coshaho  阅读(1262)  评论(0编辑  收藏  举报