1.通过jedis连接redis单机(自行创建maven项目)
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.1.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
package Day01;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import redis.clients.jedis.Jedis;
public class AppTest
{
/**
* 单实例连接redis
*/
@Test
public void testJedisSingle()
{
Jedis jedis = new Jedis("192.168.153.128", 6379);
jedis.set("name", "bar");
String name = jedis.get("name");
System.out.println(name);
jedis.close();
}
}
2.通过连接池连接
通过单实例连接redis不能对redis连接进行共享,可以使用连接池对redis连接进行共享,提高资源利用率,使用jedisPool连接redis服务,如下代码。
/*
* 连接池连接redis
* */
@Test
public void pool() {
// 创建redis连接池的配置对象
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(20);
config.setMaxTotal(50);
// 创建连接池的对象
JedisPool pool = new JedisPool(config, "192.168.153.128", 6379);
// 从连接池中获得一个连接
Jedis jedis = pool.getResource();
String name = jedis.get("name");
System.out.println(name);
// 关闭连接
jedis.close();
}