springboot集成redis
1、引入依赖
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
2、配置类
public interface RedisConfig { String host = "62.234.155.68"; int port = 6379; int timeout = 0; // 连接池最大连接数(使用负值代表没有限制) int maxActive = 200; // 连接池中的最大空闲连接 int maxIdle = 8; // 连接池中的最小空闲连接 int minIdle = 8; // 连接池最大阻塞等待时间(负值代表没有限制) long maxWait = -1; String password = "****"; }
3、工具类
public class RedisUtil { private static JedisPool jedisPool; static { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(RedisConfig.maxIdle); jedisPoolConfig.setMaxWaitMillis(RedisConfig.maxWait); jedisPoolConfig.setMaxTotal(RedisConfig.maxActive); jedisPoolConfig.setMinIdle(RedisConfig.minIdle); jedisPool = new JedisPool(jedisPoolConfig, RedisConfig.host, RedisConfig.port, RedisConfig.timeout, null); System.out.println(jedisPool.isClosed()); } public static void set(String key, String value){ try(Jedis jedis = getJedis()){ jedis.set(key, value); } } public static String get(String key){ try(Jedis jedis = getJedis()){ return jedis.get(key); } } public static long setNx(String key, String value){ try(Jedis jedis = getJedis()){ return jedis.setnx(key, value); } } public static void hashSet(String key, String field, String value){ try(Jedis jedis = getJedis()){ jedis.hset(key, field, value); } } public static void hashGet(String key, String field){ try(Jedis jedis = getJedis()){ jedis.hget(key, field); } } private static Jedis getJedis(){ return jedisPool.getResource(); } }