jedis 使用示例

jedis 是 Redis 官方首选的 Java 客户端开发包,上手比较容易。

我们可以去以下地址下载:http://github.com/xetorthio/jedis/releases

或者加入如下Maven依赖:

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

在尝试编写代码,读写数据时,请确保Redis已经正确安装。这里提供一个Windows下安装Redis的例子:

http://blog.csdn.net/yanan_seachange/article/details/42525277

jedis提供了以下三种操作方式:

  1. 单机单连接方式:此方式仅建议用于开发环境做调试用。
  2. 单机连接池方式:此方式适用于仅使用单个Redis实例的场景
  3. 多机分布式+连接池方式:此方式适用规模较大的系统,往往会有多个Redis实例做负载均衡。并且还实现主从备份,当主实例发生故障时,切换至从实例提供服务。

类似于Memcached的客户端,Jedis也提供了客户端分布式操作的方式,采用一致性哈希算法。

单机单连接方式

package com.lemon.redis.test;

import redis.clients.jedis.Jedis;

public class JedisTest {
	
	public static void main(String[] args) {
		Jedis jedis = new Jedis("localhost");
		jedis.set("foo", "bar");
		String value = jedis.get("foo");
		System.out.println("foo is:"+value);
	}
}

不出意外,应该有下图输出:


上面的例子是很简单:我们使用了单连接来操作Redis,当程序结束后,及时我们关闭了Redis服务,“foo”仍然被Redis保存下来。


单机连接池方式

package com.lemon.redis.test;

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

public class JedisPoolTest {

	static JedisPoolConfig config;
	static JedisPool jedisPool;
	
	static {
		// 初始化连接池配置对象
		config = new JedisPoolConfig();
		config.setMaxIdle(10);
		config.setMaxTotal(30);
		config.setMaxWaitMillis(3*1000);
		// 实例化连接池
		jedisPool=new JedisPool(config, "localhost", 6379);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 从连接池获取Jedis连接
		Jedis jedisConn = jedisPool.getResource();
		jedisConn.del("cities"); 
		jedisConn.lpush("cities","北京"); 
		jedisConn.lpush("cities","上海"); 
		jedisConn.lpush("cities","广州"); 
		System.out.println(jedisConn.lrange("cities",0,-1)); 
		// 释放连接
		close(jedisConn, jedisPool);

	}
	
	private static void close(Jedis jedisConn,JedisPool pool){
		if(jedisConn!=null &&pool!=null){
			pool.returnResource(jedisConn);
		}
		if(pool!=null){
			jedisPool.destroy();
		}
	}

}

上面的例子中,首先初始化了Jedis连接池,然后取出一个Jedis连接,接着使用了lpush添加了三个字符串,然后使用了lrange打印出了“cities”中存放的数据。

这两个函数的详情如下:

public Long lpush(String key,
                  String... strings)

Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key does not exist an empty list is created just before the append operation. If the key exists but is not a List an error is returned.


public Long lpush(String key,
                  String... strings)

Return the specified elements of the list stored at the specified key. Start and end are zero-based indexes. 0 is the first element of the list (the list head), 1 the next element and so on.

For example LRANGE foobar 0 2 will return the first three elements of the list.

start and end can also be negative numbers indicating offsets from the end of the list. For example -1 is the last element of the list, -2 the penultimate element and so on.

Consistency with range functions in various programming languages

Note that if you have a list of numbers from 0 to 100, LRANGE 0 10 will return 11 elements, that is, rightmost item is included. This may or may not be consistent with behavior of range-related functions in your programming language of choice (think Ruby's Range.new, Array#slice or Python's range() function).

LRANGE behavior is consistent with one of Tcl.

Out-of-range indexes

Indexes out of range will not produce an error: if start is over the end of the list, or start > end, an empty list is returned. If end is over the end of the list Redis will threat it just like the last element of the list.

Time complexity: O(start+n) (with n being the length of the range and start being the start offset)



连接池+分布式

package com.lemon.redis.test;

import java.util.ArrayList;
import java.util.List;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class MultipleJedisPoolTest {

	static JedisPoolConfig config;
	static ShardedJedisPool sharedJedisPool;
	
	static {
		// 生成多机连接List
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		shards.add( new JedisShardInfo("127.0.0.1", 6379) );
		shards.add( new JedisShardInfo("192.168.1.6", 6379) );
		
		// 初始化连接池配置对象
		config = new JedisPoolConfig();
		config.setMaxIdle(10);
		config.setMaxTotal(30);
		config.setMaxWaitMillis(3*1000);
		// 实例化连接池
		sharedJedisPool = new ShardedJedisPool(config, shards);

	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 从连接池获取Jedis连接
		ShardedJedis shardedJedisConn = sharedJedisPool.getResource();
		shardedJedisConn.set("Lemon", "Hello,my name is Lemon");
		System.out.println(shardedJedisConn.get("Lemon")); 
		// 释放连接
		close(shardedJedisConn, sharedJedisPool);

	}
	
	private static void close(ShardedJedis shardedJedis,ShardedJedisPool sharedJedisPool){
		if(shardedJedis!=null &&sharedJedisPool!=null){
			sharedJedisPool.returnResource(shardedJedis);
		}
		if(sharedJedisPool!=null){
			sharedJedisPool.destroy();
		}
	}
}

输出如下:



  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值