SpringBoot集成Redis如何使用RedisRepositories
作者:慢热型
时间:2023-04-27
来源:互联网
浏览:0
SpringBoot集成Redis1.添加redis依赖org.springframework.bootspring-boot-starter-data-redisorg.apache.commonscommons-pool22.在application.properties中添加redis配置信息spring.redis.host=127.0.0.1#Redis服务器连接端口spring.redis.port=6379#Redis服务器连接密码(默认为空)spring.redis.password=#连
SpringBoot集成Redis
1.添加redis依赖
org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2
2.在application.properties中添加redis配置信息
spring.redis.host=127.0.0.1 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接池最大连接数(使用负值表示没有限制) spring.redis.lettuce.pool.max-active=8 # 连接池最大阻塞等待时间(使用负值表示没有限制) spring.redis.lettuce.pool.max-wait=-1 # 连接池中的最大空闲连接 spring.redis.lettuce.pool.max-idle=8 # 连接池中的最小空闲连接 spring.redis.lettuce.pool.min-idle=0 # 连接超时时间(毫秒) spring.redis.timeout=30000
3.SpringBoot启动类中添加注解配置
@EnableCaching
@EnableRedisRepositories
//注解开启使用RedisRepositories
//CRUD操作将会操作redis中的数据
@SpringBootApplication
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}4.创建实体类Entity
@Data
@RedisHash("user")
//RedisHash非常重要
//user表示在redis中新建user集合
//之后所有的UserEntity的保存操作全部会保存在user这个集合中
//保存时Key的格式为——user:id
public class UserEntity{
@Id
private Long id;
private String name;
private Integer age;
private Date createTime = new Date();
}5.创建Dao层——数据操作层
@Repository public interface UserDao extends CrudRepository{ }
6.创建Service层——服务层
@Service
public class UserService {
@Autowired
private UserDao userDao;
//因为使用了RedisRepositories,所以简单的crud将不用使用RedisTemplate
// @Autowired
// private RedisTemplate redisTemplate;
/**
* 按user:id的方式存入redis
* @param user
*/
public void save(UserEntity user){
//redisTemplate.opsForValue().set(new Random().nextDouble() + "",user);
userDao.save(user);
}
/**
* 根据key从redis中查找对应value
* @param id
* @return
*/
public UserEntity findOne(Long id){
//UserEntity user = (UserEntity) redisTemplate.opsForValue().get(key);
UserEntity user = userDao.findById(id).get();
return user;
}
}7.创建Controller层——控制层
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
/**
* 保存到redis中
* @return
*/
@GetMapping("save")
public String save(){
UserEntity user = new UserEntity();
user.setName(String.valueOf(new Random().nextInt(100000)));
user.setAge(new Random().nextInt(100000));
userService.save(user);
System.out.println(user.toString());
return "success";
}
/**
* 根据key从redis中查找value
* @param id
* @return
*/
@GetMapping("find/{id}")
public String find(@PathVariable Long id){
UserEntity user = userService.findOne(id);
System.out.println(user);
return "success";
}
}8.redis配置类
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
} Redis中的结构为

redis封装工具类
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
// =============================common============================
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map
作者最新文章
网易2026年Q2财报:营收301亿元,游戏收入增10%,三款重点新游披露进展
2026-09-08 17:51
PDF怎么添加页码?页码位置和起始页怎么设置?
2026-09-03 09:11
图片文件怎么转换成PDF?多张图片如何按顺序合成?
2026-09-02 19:33
CorelDRAW绘制正弦曲线的两种方法:贝塞尔工具与变形工具
2026-09-02 16:08
Excel工作表制作教程:设计易填写、易统计的业务表
2026-09-02 12:11
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















