1、Redis依赖包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-redis</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
2、application.properties
#session 的过期时间,默认值为30分钟
spring.redis.timeout=1800
# 本地redis
redis.host=127.0.0.1
# 本地redis端口号
redis.port=6379
# Redis服务器连接密码(默认为空),本地运行时没有配置password
redis.password=
# 连接超时时间(毫秒)
redis.timeout=10000
# 连接池最大连接数(使用负值表示没有限制)
redis.pool.max-active=100
# 连接池最大阻塞等待时间(使用负值表示没有限制)
redis.pool.max-wait=-1
# 连接池中的最大空闲连接
redis.pool.max-idle=20
# 连接池中的最小空闲连接
redis.pool.min-idle=8
3、JedisConfig
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* Jedis配置,项目启动注入JedisPool
*
* @author 王文龙
*/
@Configuration
@EnableAutoConfiguration
@PropertySource("classpath:application.properties")
@ConfigurationProperties(prefix = "redis")
public class JedisConfig {
/**
* LOGGER
*/
private static final Logger LOGGER = LoggerFactory.getLogger(JedisConfig.class);
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private int port;
@Value("${redis.password}")
private String password;
@Value("${redis.timeout}")
private int timeout;
@Value("${redis.pool.max-active}")
private int maxActive;
@Value("${redis.pool.max-wait}")
private int maxWait;
@Value("${redis.pool.max-idle}")
private int maxIdle;
@Value("${redis.pool.min-idle}")
private int minIdle;
@Bean
public JedisPool redisPoolFactory() {
try {
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWait);
jedisPoolConfig.setMaxTotal(maxActive);
jedisPoolConfig.setMinIdle(minIdle);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
LOGGER.info("初始化Redis连接池JedisPool成功!地址: " + host + ":" + port);
return jedisPool;
} catch (Exception e) {
LOGGER.error("初始化Redis连接池JedisPool异常:" + e.getMessage());
}
return null;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
}
4、实体类
@Data
@ToString
public class Sys_user implements Serializable {
private int user_id; //userID
private String user_nick_name; //user昵称
private String user_name;//user真实姓名
private String user_password; //user密码
private String user_phone;//user电话
private String user_email;//user邮箱
private String user_sex;//user性别
private String user_birthday;//user生日
}
5、sql语句及持久层,我这里图个方便写的注解sql语句,跟xml的sql是一样的
public interface SysUserDao {
@Select("select * from sys_user where user_id=#{user_id} ")
Sys_user findUserById(@Param("user_id") int user_id);
@Update("update sys_user set user_name = #{userName} where user_id = #{id}")
int update(Integer id ,String userName);
}
6、单元测试
/**
* @Author 王文龙
* @Date 2019-05-30 15:24
* @Version 1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {
@Resource
private SysUserDao sysUserDao;
@Resource
private RedisTemplate redisTemplate;
@Test
public void testFindById() {
//模拟id查询入参
int id = 100081;
//设置 存入Redis的key
String key = "user_" + id;
//操作字符串
ValueOperations<String, SysUser> operations = redisTemplate.opsForValue();
//检测key是否在redis中存在
boolean hasKey = redisTemplate.hasKey(key);
//如果 存在,从redis中获取数据,如果不存在就先查数据库,然后将查到的值再次放入redis中
if (hasKey) {
//从redis中获取缓存的数据
Sys_user sys_user = operations.get(key);
System.err.println(sys_user);
} else {
//从数据库获取数据
Sys_user userById = sysUserDao.findUserById(id);
//如果不为空就将数据写入redis中并打印输出
if (userById != null) {
//插入缓存
operations.set(key, userById);
System.err.println(userById);
}
}
}
@Test
public void testUpdate() {
//操作字符串
ValueOperations<String, SysUser> operations = redisTemplate.opsForValue();
//更新数据库
int result = sys_userDao.update(100079, "大白兔");
if (result != 0) {
String key = "user_" + 100079;
//检测key是否在redis中存在
boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
//删除缓存中的key
redisTemplate.delete(key);
//检查下是否已经真的删除
boolean hasKey1 = redisTemplate.hasKey(key);
System.err.println("hasKey1 是否存在Redis中 " + hasKey1);
}
//将更新的数据再次放入redis中
SysUser userById = sysUserDao.findUserById(100079);
if (userById != null) {
//放入缓存
operations.set(key, userById);
//检查新数据是否存在
boolean newHasKey = redisTemplate.hasKey(key);
System.err.println("newHasKey 是否存在Redis中 " + newHasKey);
System.err.println("将最新的数据从缓存中取出打印 : " + operations.get(key));
}
}
}
}
提示:如果没学过或用过redis的小伙伴,可以先百度下redis的作用,这是一个简单的案例,小伙伴儿们可以debug一下,查看每一步的结果,以便加深印象,或拓宽知识面,想一想为什么这么做,能不能换另外一种方式做,这也是我这篇文章不写文字的缘故,感谢查看本篇文章