Springboot集成整合Redis
【前言】记录整理springboot集成Redis代码。单机版,哨兵集群,cluster集群,完整代码已上传github
集成单机版Redis
1.核心maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.配置文件application.yml
spring:
redis:
database: 0
host: 172.28.13.140
port: 6379
password: China1234
timeout: 10000
jedis:
pool:
max-active: 500
min-idle: 5
max-idle: 50
max-wait: 60000
3.工具类
3.1 采用JedisPool(推荐)
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* @description:
* @author: uwank171
* @date: 2022/9/1 13:17
*/
@Configuration
public class JedisConfig {
/**配置文件中部分参数没有加载进去*/
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.database}")
private int database;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.jedis.pool.max-active}")
private int maxTotal;
@Value("${spring.redis.jedis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis;
private static JedisPool jedisPool = null;
public Jedis getJedis() {
if (jedisPool == null) {
jedisPool();
}
if (jedisPool != null) {
return jedisPool.getResource();
}
return null;
}
public void closeJedis(Jedis jedis) {
try {
if (jedis != null) {
jedis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Bean("jedisPool")
public JedisPool jedisPool() {
if (jedisPool == null) {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMinIdle(minIdle);
jedisPoolConfig.setMaxIdle(maxTotal);
jedisPoolConfig.setMaxTotal(maxTotal);
jedisPoolConfig.setBlockWhenExhausted(true);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
jedisPoolConfig.setTestOnBorrow(true);
jedisPoolConfig.setTestOnReturn(true);
jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password, database);
}
return jedisPool;
}
}
/** JedisUtil类 ,可以自定义添加其它方法*/
import com.redmaple.common.config.JedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
/**
* @description: 再次封装的目的是为了关闭jedis连接,释放资源。
* 因为直接使用 Jedis jedis = jedisConfig.getJedis() 操作,在代码中容易忘记 close,且比较麻烦。
* @author: uwank171
* @date: 2022/9/1 13:43
*/
@Component
public class JedisUtil {
@Autowired
private JedisConfig jedisConfig;
/**
* 判断是否存在key
* @param key
* @param timeoutSeconds
* @return
*/
public boolean expire(String key, int timeoutSeconds) {
Jedis jedis = jedisConfig.getJedis();
try {
jedis.expire(key, timeoutSeconds);
return true;
} catch (Exception e) {
// 打印日志的包没有引入
//lo1g.error(">>>>> JedisUtils error " + e);
System.err.println(">>>>> JedisUtils error " + e);
return false;
} finally {
jedisConfig.closeJedis(jedis);
}
}
/**
* 存储数据
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
Jedis jedis = jedisConfig.getJedis();
try {
return jedis.set(key, value);
} catch (Exception e) {
System.err.println(">>>>> JedisUtils error " + e);
return null;
} finally {
jedisConfig.closeJedis(jedis);
}
}
/**
* 获取数据
* @param key
* @return
*/
public String get(String key) {
Jedis jedis = jedisConfig.getJedis();
try {
return jedis.get(key);
} catch (Exception e) {
System.err.println(">>>>> JedisUtils error " + e);
return null;
} finally {
jedisConfig.closeJedis(jedis);
}
}
/**
* 删除数据
* @param key
* @return
*/
public boolean del(String key) {
Jedis jedis = jedisConfig.getJedis();
try {
jedis.del(key);
return true;
} catch (Exception e) {
System.err.println(">>>>> JedisUtils error " + e);
return false;
} finally {
jedisConfig.closeJedis(jedis);
}
}
/**
* 判断是否存在key
* @param key
* @return
*/
public boolean exists(String key) {
Jedis jedis = jedisConfig.getJedis();
try {
return jedis.exists(key);
} catch (Exception e) {
System.err.println(">>>>> JedisUtils error " + e);
return false;
} finally {
jedisConfig.closeJedis(jedis);
}
}
}
3.2 直接new Jedis()
这么操作确实很简易,但是需要手动关闭close,使用过多的会比较繁琐
import redis.clients.jedis.Jedis;
/**
* @description: 简易版,可以按需求自己修改
* @author: uwank171
* @date: 2022/9/1 13:43
*/
public class JedisUtil2 {
private static String host = "172.28.13.140";
private static int port = 6379;
public static void main(String[] args) {
Jedis jedis = null;
try {
jedis = new Jedis(host, port);
String key = "redis_key1";
String value = "redis_1001";
// 存入数据
jedis.set(key, value);
// 获取数据
System.out.println(jedis.get(key));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
3.3 RedisTemplate 序列化方式
/**
* @description: 注意需要序列化的对象一定要实现Serializable接口
* @author: uwank171
* @date: 2022/9/1 13:43
*/
@Component
public class JedisUtil3 {
@Resource
private RedisTemplate<String, Object> redisTemplate;
public void setObject(String key, Object object) {
redisTemplate.opsForValue().set(key, object);
}
public Object getObjet(String key) {
return redisTemplate.opsForValue().get(key);
}
}
/** 注意需要序列化的对象一定要实现Serializable接口 */
@Data
public class UserEntity implements Serializable {
private Long userId;
private String userName;
}
4.测试Controller
@RestController
public class RedisStandloneController {
@Autowired
private JedisUtil jedisUtil;
@GetMapping("/setKey")
public String setKey(String key, String value) {
jedisUtil.set(key, value);
return "===setKey完成===key:" + key + " value:" + value;
}
@GetMapping("/getKey")
public String getKey(String key) {
String value = jedisUtil.get(key);
return "===getKey完成===key:" + key + " value:" + value;
}
//=========================================================================
@Autowired
private JedisUtil3 jedisUtil3;
@GetMapping("/setObj")
public String setObj(String key, String value) {
jedisUtil3.setObject(key, value);
return "===setKey完成===key:" + key + " value:" + value;
}
@GetMapping("/getObj")
public String getObj(String key) {
String value = (String) jedisUtil3.getObjet(key);
return "===getKey完成===key:" + key + " value:" + value;
}
以上就是整合单记版的redis,最后的RedisTemplate方法还可以在项目启动时重新修改序列化在注入到容器中更方便点,后续再更新。
如果该文章能够帮助到你,希望麻烦点赞收藏下,谢谢。