Java 使用Jedis操作Redis

redis是很流行的缓存工具,常用在web和db之间,其有多种语言的client,这里简单记录下java client jedis的常用用法。

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.Test;
    import redis.clients.jedis.Jedis;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;

    /**
    * Created by kongkong on 16-3-15.
    */
    public class App {
        private static final Logger logger = LoggerFactory.getLogger(App.class);
        private Jedis jedis;

        @BeforeTest
        public void before() {
            //连接redis服务器,ip地址,端口
            jedis = new Jedis("pc", 6379);
            //密码认证
            jedis.auth("admin");
        }

        @Test
        public void testSetAndGet() {
            //存储普通字符串
            jedis.set("name", "Tom");
            jedis.set("age", "18");

            System.out.println(jedis.get("name"));
            System.out.println(jedis.get("age"));

            //字符串拼接
            jedis.append("name", "Tom");
            System.out.println(jedis.get("name"));

            //删除键值对
            jedis.del("name");
            System.out.println(jedis.get("name")); //null

            jedis.mset("name", "Lily", "age", "18", "sex", "F");
            //给数字执行+1操作
            jedis.incr("age");
            System.out.println(jedis.get("age"));
            System.out.println("end");
        }

        @Test
        public void testMap() {
            //redis操作hashmap
            HashMap<String,String> hashMap = new HashMap<String, String>();
            hashMap.put("name", "Lucy");
            hashMap.put("age", "15");
            hashMap.put("sex", "F");

            jedis.hmset("user", hashMap);

            //读取hashmap
            List<String> mapGet = jedis.hmget("user", "name", "age", "sex");
            System.out.println(mapGet);

            //删除redis中map的某个属性
            jedis.hdel("user", "age");
            System.out.println(jedis.hkeys("user"));
            System.out.println("end");
        }

        @Test
        public void testList() {
            //操作list
            jedis.flushAll();
            jedis.lpush("users", "Tom");
            jedis.lpush("users", "Lily");
            jedis.rpush("users", "aaa");
            System.out.println(jedis.lrange("users", 0, -1));
        }

        @Test
        public void testSet() {
            //操作Set
            jedis.del("users");
            jedis.sadd("users", "Tom");
            jedis.sadd("users", "Lily");
            jedis.sadd("users", "who");
            System.out.println(jedis.smembers("users"));
            logger.info(jedis.smembers("users").toString());
            logger.info("Hello");
        }

        @Test
        public void testSort() {
            //Redis排序
            jedis.del("num");
            jedis.lpush("num", "1");
            jedis.lpush("num", "2");
            jedis.rpush("num", "3");
            jedis.lpush("num", "4");

            logger.info(jedis.lrange("num", 0, -1).toString());
            logger.info(jedis.sort("num").toString());
        }

        @Test
        public void testPool() throws Exception{
            //测试连接池
            for(int i=1; i<=5; i++) {
                new Thread(runnable).start();
                System.out.println(i);
            }
            Thread.sleep(5000);
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Jedis jedis1 = RedisUtil.getJedis();
                String key = ""+ new Date().getTime();
                System.out.println(key);
                jedis1.set(key, "1");
                RedisUtil.returnResource(jedis1);
            }
        };
    }

RedisUtil.java:

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

    /**
     * Created by kongkong on 16-3-16.
     */
    public class RedisUtil {
        private static String ADDR = "pc";
        private static int PORT = 6379;
        private static String AUTH = "admin";
        private static int MAX_ACTIVE = 200;
        private static int MAX_IDLE = 20;
        private static int MAX_WAIT = 50 * 1000;
        private static int TIME_OUT = 1000;
        private static boolean TEST_ON_BORROW = true;
        private  static JedisPool jedisPool = null;
        /**
         * 初始化Redis连接池
         */
        static {
            try {
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxTotal(MAX_ACTIVE);
                config.setMaxIdle(MAX_IDLE);
                config.setMaxWaitMillis(MAX_WAIT);
                config.setTestOnBorrow(TEST_ON_BORROW);
                jedisPool = new JedisPool(config, ADDR, PORT, TIME_OUT, AUTH);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public synchronized static Jedis getJedis() {
            try {
                if(null != jedisPool) {
                    Jedis resource = jedisPool.getResource();
                    return resource;
                } else {
                    return null;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        public static void returnResource(final Jedis jedis) {
            if(null != jedis) {
                jedis.close();
            }
        }
    }

版权声明

本站文章、图片、视频等(除转载外),均采用知识共享署名 4.0 国际许可协议(CC BY-NC-SA 4.0),转载请注明出处、非商业性使用、并且以相同协议共享。

© 空空博客,本文链接:https://www.yeetrack.com/?p=1115