zoukankan      html  css  js  c++  java
  • Jedis操作Redis实例

    简介


    Jedis Client是Redis官网推荐的一个面向java客户端,库文件实现了对各类API进行封装调用。

    Jedis源码工程地址:https://github.com/xetorthio/jedis

    使用


    Redis Client最好选用与服务端对应的版本,本例中使用Redis 3.2.9客户端使用jedis -2.9.0,Maven工程添加如下引用即可。

    <dependency>
             <groupId>redis.clients</groupId>
             <artifactId>jedis</artifactId>
             <version>2.9.0</version>
             <type>jar</type>
             <scope>compile</scope>
    </dependency>

    注意事项

    Redis Client拥有众多对接版本,本项目目前使用Jedis为官方推荐Java对接客户端,是基于其对Redis良好的版本支持和API对接,另外编码中尽量避免使用废弃接口。

    Redis目前正在新版过渡期,3.0版本暂未稳定,但是由于3.0版本提供了最新的集群功能,可能在日后稳定版发布以后升级到3.0,目前使用的Jedis支持3.0的目前版本API。


    Jedis基本使用


    普通使用

    Jedis jedis = new Jedis("localhost");
    jedis.set("foo", "bar");
    String value = jedis.get("foo");

    Jedis池

    JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost");
    /// Jedis implements Closeable. Hence, the jedis instance will be auto-closed after the last statement.try (Jedis jedis = pool.getResource()) {  /// ... do stuff here ... for example
      jedis.set("foo", "bar");  
      String foobar = jedis.get("foo");
      jedis.zadd("sose", 0, "car"); 
      jedis.zadd("sose", 0, "bike"); 
      Set<String> sose = jedis.zrange("sose", 0, -1);
    }/// ... when closing your application:pool.close();
    JedisPoolConfig config = new JedisPoolConfig();
    		//最大连接数
    		config.setMaxTotal(10);
    		//最大空闲连接数
    		config.setMaxIdle(5);
    		//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
    		config.setMaxWaitMillis(1000);
    		//在获取连接的时候检查有效性, 默认false
    		config.setTestOnBorrow(true);
    		//在获取返回结果的时候检查有效性, 默认false
    		config.setTestOnReturn(true);
    		JedisPool pool = new JedisPool(config, "192.168.245.153",6379);
    
    		try (Jedis jedis = pool.getResource()) {
    		  jedis.set("foo", "bar");
    		  String foobar = jedis.get("foo");
    		  jedis.zadd("sose", 0, "car"); jedis.zadd("sose", 0, "bike"); 
    		  Set<String> sose = jedis.zrange("sose", 0, -1);
    		}
    		pool.close();

    Jedis常用操作


    String的简单追加

    Jedis jedis = new Jedis("192.168.245.153",6379);
    jedis.append("foo", "bar");

    Jedis存放List

    jedis.lpush("s", "1","2","3","4");

    Jedis操作Hash值

    Jedis jedis = new Jedis("192.168.245.153",6379);
    jedis.hset("hash", "key1", "v1");
    jedis.hset("hash", "key2", "v2");
    jedis.hset("hash", "key3", "v4");
    //获取值
    String hget = jedis.hget("hash", "key3");
    System.out.println(hget);

    Jedis操作Set值

    jedis.sadd("set", "1","2","3");
    //获取值
    Set<String> smembers = jedis.smembers("set");
    System.out.println(smembers.toString());

    Jedis操作有序集合

    Map<String,Double> scoreMembers = new HashMap<>();
    scoreMembers.put("a", 1d);
    scoreMembers.put("c", 3d);
    scoreMembers.put("t", 2d);
    jedis.zadd("st", scoreMembers);
    //获取有序集合的成员数
    Long zcard = jedis.zcard("st");
    ScanResult<Tuple> zscan = jedis.zscan("st", ScanParams.SCAN_POINTER_START);
    List<Tuple> result = zscan.getResult();
    Iterator<Tuple> iterator = result.iterator();
    while (iterator.hasNext()) {
    	Tuple next = iterator.next();
    	String element = next.getElement();
    	System.out.println(element);
    }

    Jedis存放(序列化)Bean对象

    Jedis jedis = new Jedis("192.168.245.153",6379);
    
    Person p1 = new Person();
    p1.setAge("20");
    p1.setName("joy");
    p1.setId(1);
    //存放序列化值
    try {
    	ByteArrayOutputStream bout = new ByteArrayOutputStream();
    	ObjectOutputStream oout = new ObjectOutputStream(bout);
    	oout.writeObject(p1);
    	byte[] byteArray = bout.toByteArray();
    	jedis.set("person:1".getBytes(), byteArray);
    } catch (IOException e) {
    	// TODO Auto-generated catch block
    	e.printStackTrace();
    }
    
    //反序列化
    byte[] bs = jedis.get("person:1".getBytes());
    ObjectInputStream oin;
    try {
    	ByteArrayInputStream bin = new ByteArrayInputStream(bs);
    	oin = new ObjectInputStream(bin);
    	Person p = (Person)oin.readObject();
    	System.out.println(p.getName());
    } catch (IOException e) {
    	e.printStackTrace();
    } catch (ClassNotFoundException e) {
    	e.printStackTrace();
    }

    Jedis存放对象(转化成Map)

    Jedis jedis = new Jedis("192.168.245.153",6379);
    		
    		//存放p1对象
    		Person p1 = new Person();
    		p1.setAge("20");
    		p1.setName("joy");
    		p1.setId(1);
    		try {
    			Map<String, Object> bean2map = BeanUtils.bean2map(p1);
    			Map<String,String> map = new HashMap<>();
    			Set<Entry<String, Object>> entrySet = bean2map.entrySet();
    			Iterator<Entry<String, Object>> iterator = entrySet.iterator();
    			while(iterator.hasNext()) {
    				Entry<String, Object> next = iterator.next();
    				map.put(next.getKey(), String.valueOf(next.getValue()));
    			}
    			//存放map
    			jedis.hmset("person", map);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		String hget = jedis.hget("person", "name");
    		System.out.println(hget);


    Jedis排序

    简单排序

    //降序
    jedis.lpush("s", "1","2","3","4");
    List<String> sort = jedis.sort("s",new SortingParams().desc());
    System.out.println(sort);
    
    //升序
    jedis.lpush("s", "1","2","3","4");
    List<String> sort = jedis.sort("s",new SortingParams().asc());
    System.out.println(sort);










    查看原文:http://www.coder306.cn/?p=196
  • 相关阅读:
    哈哈,原来这叫做“松鼠症”……并谈谈我建议的学习方法
    入坑IT十年(二)技术以外
    入坑IT都快十年了
    也来谈谈IT培训
    技术,是不是越新越好?
    十年之后再看“面向对象”
    话说,你这样根本就不应该去“创业型”公司
    我为什么不做外包
    NetTopologySuite Geometry&WKT&WKB&GeoJSON互转
    wpf 打印图片
  • 原文地址:https://www.cnblogs.com/coder306/p/13087679.html
Copyright © 2011-2022 走看看