首页 > 代码库 > Java 操作 Redis 高级

Java 操作 Redis 高级

/Users/sherry/WorkPath/Git/Web/redisDemo/src/main/java/org/zln/utils/JedisUtils.java

package org.zln.utils;import org.apache.commons.lang3.StringUtils;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;/** * Created by sherry on 16/9/13. */public class JedisUtils {    private static Logger logger = LogManager.getLogger();    private static JedisPool pool = null;    private static final String URL = "127.0.0.1";    private static final int PORT = 6379;    private static Jedis jedis = null;    static {        pool = new JedisPool(new JedisPoolConfig(), URL,PORT);    }    public static Jedis getRedisCon(String password){        jedis = pool.getResource();        if (StringUtils.isNotEmpty(password)){            logger.info("以密码:"+password+" 登陆 redis");            jedis.auth(password);        }        logger.info(jedis.ping());        return jedis;    }    public static void closeRedisCon(Jedis jedis){        if (jedis!=null){            jedis.close();        }    }    public static void closeApp(){        //关闭应用程序的时候执行        pool.destroy();    }}

 

/Users/sherry/WorkPath/Git/Web/redisDemo/src/main/java/org/zln/main/JedisMain.java

package org.zln.main;import org.apache.logging.log4j.LogManager;import org.apache.logging.log4j.Logger;import org.zln.utils.JedisUtils;import redis.clients.jedis.Jedis;import java.io.*;import java.util.*;/** * Created by sherry on 16/9/13. */public class JedisMain {    private static Logger logger = LogManager.getLogger();    public static void main(String[] args) {        Jedis jedis = JedisUtils.getRedisCon("");//        stringTest(jedis);////        listTest(jedis);////        mapTest(jedis);////        objTest(jedis);        objListTest(jedis);//        将这个Jedis实例归还给JedisPool。        JedisUtils.closeRedisCon(jedis);    }    /**     * 对象列表     * @param jedis     */    private static void objListTest(Jedis jedis) {        Person person1 = new Person("name1",1);        Person person2 = new Person("name2",2);        Person person3 = new Person("name3",3);        Person person4 = new Person("name4",4);        List<Person> persons = new ArrayList<>();        persons.add(person1);        persons.add(person2);        persons.add(person3);        persons.add(person4);        try {            for (Person person:persons){                ByteArrayOutputStream bos =  new ByteArrayOutputStream();                ObjectOutputStream oos =  new ObjectOutputStream(bos);                oos.writeObject(person);                byte [] byteArray = bos.toByteArray();                oos.close();                bos.close();                logger.info("写入对象:"+person);                jedis.lpush("persons".getBytes(),byteArray);            }            List<byte[]> personsBytes = jedis.lrange("persons".getBytes(),0,10);            for (byte[] bs:personsBytes){                ByteArrayInputStream bis =  new ByteArrayInputStream(bs);                ObjectInputStream inputStream =  new ObjectInputStream(bis);                Person readObject = (Person) inputStream.readObject();                logger.info( " 读取对象 \t" + readObject.toString());                inputStream.close();                bis.close();            }        } catch (IOException|ClassNotFoundException e) {            e.printStackTrace();        }        jedis.del("persons".getBytes());    }    /**     * 存储对象     * @param jedis     */    private static void objTest(Jedis jedis) {        Person person = new Person();        person.setAge(27);        person.setName("卡卡卡");        ByteArrayOutputStream bos =  new ByteArrayOutputStream();        try {            ObjectOutputStream oos =  new ObjectOutputStream(bos);            oos.writeObject(person);            byte [] byteArray = bos.toByteArray();            oos.close();            bos.close();            String setObjectRet = jedis.set(person.getName().getBytes(), byteArray);            logger.info( " set object return \t" + setObjectRet);            byte [] bs = jedis.get( person.getName().getBytes());            ByteArrayInputStream bis =  new ByteArrayInputStream(bs);            ObjectInputStream inputStream =  new ObjectInputStream(bis);            Person readObject = (Person) inputStream.readObject();            logger.info( " read object \t" + readObject.toString());            inputStream.close();            bis.close();        } catch (IOException|ClassNotFoundException e) {            e.printStackTrace();        }        jedis.del(person.getName());    }    /**     * 存储 Map     * @param jedis     */    private static void mapTest(Jedis jedis) {        Map<String,String> user =  new HashMap<String,String>();        user.put( "name" ,  "cd" );        user.put( "password" ,  "123456" );        jedis.hmset("user",user);        // mapkey 个数        System.out.println(String.format ( "len:%d" , jedis.hlen( "user" )));//map中的所有键值        System.out.println(String.format ( "keys: %s" , jedis.hkeys( "user" ) ));//map中的所有value        System.out.println(String.format ( "values: %s" , jedis.hvals( "user" ) ));//取出map中的name字段值        List<String> rsmap = jedis.hmget( "user" ,  "name" , "password" );        System.out.println(rsmap);//删除map中的某一个键值 password        jedis.hdel( "user" ,  "password" );        System.out.println(jedis.hmget( "user" ,  "name" ,  "password" ));        jedis.del("user");    }    /**     * 存储列表     * @param jedis     */    private static void listTest(Jedis jedis) {        jedis.lpush("tutorial-list", "Redis");        jedis.lpush("tutorial-list", "Mongodb");        jedis.lpush("tutorial-list", "Mysql");        // 获取存储的数据并输出        List<String> list = jedis.lrange("tutorial-list", 0 ,5);        for(int i=0; i<list.size(); i++) {            System.out.println("Stored string in redis:: "+list.get(i));        }        jedis.del("tutorial-list");    }    /**     * 存储字符串     * @param jedis     */    private static void stringTest(Jedis jedis) {        //一次次添加        jedis.set("string1","一号字符串");        jedis.set("string2","二号字符串");        jedis.set("string3","三号字符串");        jedis.set("string4","四号字符串");        logger.info("获取string1:"+jedis.get("string1"));        //在已有 key 上,对 value 进行新增        jedis.append("string1","添加新字符串");        logger.info("获取string1:"+jedis.get("string1"));        //一次性添加多个键值对        jedis.mset("s1","v1","s2","v2","s3","v3");        logger.info("获取s1:"+jedis.get("s1"));        for (Iterator<String> iterator = jedis.keys("*").iterator();iterator.hasNext();){            String key = iterator.next();            logger.info(key+":"+jedis.get(key));            jedis.del(key);        }    }}

 

Java 操作 Redis 高级