1.首先我们如果是maven项目的话,需要先将redis的包导入进来,所以,在pom文件中先加上以下代码
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>
2.可以通过原始的jdbc连接数据库,也可以通过连接池去连接。
下面是一段测试代码。
①通过jdbc去连接
String host = "192.168.59.160";
int port = 6379;
Jedis jedis = new Jedis(host,port);
jedis.set("age","18");
String age = jedis.get("age");
String name = jedis.get("name");
System.out.println(age+":"+name);
②封装工具类:
最大连接数:连接池中最多存在的连接数。
最大空闲数:连接超出时,以最大空闲数为准。
最小空闲数:第一需要释放资源,次初始化连接池默认的连接数。
private static JedisPool jedisPool;
static {
InputStream stream = Utils.class.getClassLoader().getResourceAsStream("redis.properties");
Properties properties = new Properties();
try {
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
String host = properties.getProperty("redis.host");
int port = Integer.parseInt(properties.getProperty("redis.port"));
int max_total = Integer.parseInt(properties.getProperty("redis.max_total"));
int min_Idle = Integer.parseInt(properties.getProperty("redis.Min_Idle"));
int max_Idle = Integer.parseInt(properties.getProperty("redis.Max_Idle"));
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(max_total);
poolConfig.setMinIdle(min_Idle);
poolConfig.setMaxIdle(max_Idle);
jedisPool = new JedisPool(poolConfig,host,port);
}
public static Jedis getJedis(){
return jedisPool.getResource();
}
public static void closeJedis(Jedis jedis){
if(jedis!=null){
jedis.close();
}
}
我在maven的entity层的resource中加了一个配置文件。
然后加可以在我们的测试代码中写
@Test
public void add(){
Jedis jedis = Utils.getJedis();
String s = jedis.set("address", "河南");
System.out.println(s);//OK是成功 NIL是失败
}
这样就简单的实现了在idea下连接redis。
下篇文章更新redis五大基本数据类型的使用。