上一篇已经把redis安装在了linux服务器上了,接下来使用java代码去对redis进行操作,这里就需要用到redis的驱动包,和mysql数据库类似。
引入jedis(maven工程方式):
引入包后就可以使用了,使用Jedis对象就可以对redis数据库进行操作。
使用连接池的方式对redis进行连接操作:
下面我们尝试一下制作一个redis连接池的工具类:
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 自制redis连接池工具类
*/
public class MyRedisPool {
//声明静态的JedisPool属性
private static JedisPool jedisPool = null;
//静态块
static {
//获取inputStream流 读取redis.properties配置文件
InputStream inputStream = MyRedisPool.class.getClassLoader().
getResourceAsStream("redis.properties");
//Properties集合获取配置文件中的配置属性
Properties properties = new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
//创建JedisPoolConfig连接池配置对象
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(Integer.parseInt(properties.getProperty("redis.maxTotal")));
poolConfig.setMaxIdle(Integer.parseInt(properties.getProperty("redis.maxIdle")));
poolConfig.setMinIdle(Integer.parseInt(properties.getProperty("redis.minIdle")));
//创建redis连接池,把配置对象给她
jedisPool = new JedisPool(poolConfig, properties.getProperty("redis.url"), Integer.parseInt(properties.getProperty("redis.port")));
}
/**
* 得到redis操作资源对象方法
* @return Jedis操作资源对象
*/
public static Jedis getJedis() {
return jedisPool.getResource();
}
}
创建redis.properties配置文件,配置文件内容:
redis.maxTotal=50
redis.maxIdle=20
redis.minIdle=10
redis.url=127.0.0.1
redis.port=6379
测试一下我们自己操作的工具类: