1、导入jar包
Java对Redis的操作依赖于jedis,所以我们需要导入jedis的jar包
commons-pool2-2.3
jedis-2.7.0
2、编写连接池工具类
package top.ftime.wk.utils; 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; /** * @author: JAVASM * @className: JedisUtil * @description: * @date: 2021/6/6 22:55 * @version: 0.1 * @since: jdk1.8 */ public class JedisUtil { private static JedisPool jedisPool; static { InputStream inputStream = JedisUtil.class.getClassLoader().getResourceAsstream("redis.properties"); Properties properties = new Properties(); try { properties.load(inputStream); JedisPoolConfig config = new JedisPoolConfig(); //最大空闲数 config.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle"))); //最大连接数 config.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal"))); jedisPool = new JedisPool(config, properties.getProperty("host"),Integer.parseInt(properties.getProperty("port"))); } catch (IOException e) { throw new RuntimeException("配置文件加载失败"); } } /** * 获得Jedis * @return */ public static Jedis getJedis(){ return jedisPool.getResource(); } /** * 释放资源 * @param jedis */ public static void release(Jedis jedis){ //这个表示当前jedis连接 放到我们连接池中,并不是关闭了 jedis.close(); } }
3、使用
//redis 缓存 jedis.set(email, code); //两分钟后自动删除 jedis.expire(email, 120); //取值 jedis.get(email); //登录成功后,手动删除 jedis.del(email);