创建一个maven项目
![
![屏幕快照 2017-07-13 10.39.05.png](http://upload-images.jianshu.io/upload_images/2126453-b3687c0914ec3392.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
](http://upload-images.jianshu.io/upload_images/2126453-e937adf48435eb41.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
添加依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
屏幕快照 2017-07-13 10.42.59.png
单实例创建jedis
public class Client {
public static void main(String[] args) {
new Client().test1();
}
public void test1() {
// 指定redis的IP及端口号
Jedis jedis = new Jedis("127.0.0.1", 6379);
// 设置值
jedis.set("username", "jack");
// 输出获取的username
System.out.println(jedis.get("username"));
}
}
连接池方式
public class Client {
public static void main(String[] args) {
new Client().test2();
}
public void test2() {
JedisPoolConfig config = new JedisPoolConfig();
// 设置最大连接数
config.setMaxTotal(30);
// 设置最大空闲连接数
config.setMaxIdle(10);
JedisPool jedisPool = new JedisPool(config, "127.0.0.1", 6379);
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set("name", "tom");
System.out.println(jedis.get("name"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis) {
jedis.close();
}
jedisPool.close();
}
}
}