springboot使用redisRepository和redistemplate操作redis的过程解析
作者:march?of?Time 时间:2023-10-11 06:57:03
导入依赖
菜单大部分情况下不会出现变化,我们可以将其放入Redis 加快加载速度
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- commons-pool2 对象池依赖 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
基本配置
redis:
timeout: 10000ms # 连接超时时间
host: 192.168.10.100 # Redis服务器地址
port: 6379 # Redis服务器端口
database: 0 # 选择哪个库,默认0库
lettuce:
pool:
max-active: 1024 # 最大连接数,默认 8
max-wait: 10000ms # 最大连接阻塞等待时间,单位毫秒,默认 -1
max-idle: 200 # 最大空闲连接,默认 8
min-idle: 5 # 最小空闲连接,默认 0
使用RedisTemplate访问redis
RedisConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import
org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置类
*
* @author zhoubin
* @since 1.0.0
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory
redisConnectionFactory){
RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
//为string类型key设置序列器
redisTemplate.setKeySerializer(new StringRedisSerializer());
//为string类型value设置序列器
redisTemplate.setValueSerializer(new
GenericJackson2JsonRedisSerializer());
//为hash类型key设置序列器
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//为hash类型value设置序列器
redisTemplate.setHashValueSerializer(new
GenericJackson2JsonRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
return redisTemplate;
}
}
修改菜单方法:
MenuServiceImpl.java
/**
* 通过用户id获取菜单列表
*
* @return
*/
@Override
public List<Menu> getMenusByAdminId() {
Integer adminId = ((Admin)
SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
ValueOperations<String, Object> valueOperations =
redisTemplate.opsForValue();
//查询缓存中是否有数据
List<Menu> menus = (List<Menu>) valueOperations.get("menu_" + adminId);
if (CollectionUtils.isEmpty(menus)){
menus = menuMapper.getMenusByAdminId(adminId);
valueOperations.set("menu_"+adminId,menus);
}
return menus;
}
使用Redisrepository访问redis
需要声明一配置项用于启用Repository以及模板
public class RedisConfig {
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration("127.0.0.1", 6567);
redisStandaloneConfiguration.setPassword("password");//如果有密码需要通过这个函数设置密码
return new LettuceConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public JedisConnectionFactory jedisConnectionFactory(){
//如果使用jedis作为客户端也需要声明该bean 使用与上面的类似
}
@Bean
public RedisTemplate<?,?> redisTemplate(){
RedisTemplate<String,Object> template = new RedisTemplate<>();
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
template.setConnectionFactory(redisConnectionFactory());
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
template.setValueSerializer(stringSerializer);
template.setHashValueSerializer(jdkSerializationRedisSerializer);
template.setEnableTransactionSupport(true);
template.afterPropertiesSet();
return template;
}
}
实例:
entity
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;
@Accessors(chain = true)
@Data
@RedisHash(value="Student",timeToLive = 10)
public class stu implements Serializable {
public enum Gender{
MALE,FEMALE
}
private String id;
@Indexed
private String name;
private Gender gender;
//RedisHash注解用于声明该实体将被存储与RedisHash中,如果需要使用repository的数据访问形式,这个注解是必须用到的 timetoLive为实体对象在数据库的有效期
//@Indexed用于标注需要作为查询条件的属性
}
写接口
repository:
@Repository
public interface StuRepository extends CrudRepository<stu,String> {
stu findByName(String name);
//自定义查询方法,使用了@Indexed的name属性查询
}
调用:
@SpringBootTest
public class RedisApplicationTests {
@Autowired
StuRepository stuRepository;
@Test
void testSave(){
stu student = new stu().setId("0002").setName("xiaoming").setGender(stu.Gender.FEMALE);
stuRepository.save(student);//根据id更新或者新增记录
}
@Test
void testFindBy(){
//使用主键查询
assert stuRepository.findById("0002").isPresent();
//根据自定义方法查询
assert stuRepository.findByName("xiaoming") !=null;
}
}
来源:https://blog.csdn.net/qq_41358574/article/details/118087940
标签:springboot,redisRepository,redistemplate,redis
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
jdbc中class.forname的作用
2023-04-13 00:56:18
Java中的Random()函数及两种构造方法
2023-05-12 03:00:46
C#简单操作MongoDB的步骤全纪录
2023-06-25 06:52:40
Java8中对于LocalDateTime的序列化和反序列化问题
2023-11-14 15:37:41
Java深入学习图形用户界面GUI之事件处理
2023-11-29 14:14:57
Android实现表情功能
2023-03-05 06:46:27
![](https://img.aspxhome.com/file/2023/3/137463_0s.jpg)
Android实现换肤的两种思路分析
2023-03-25 13:54:18
Android完整Socket解决方案
2023-12-22 14:42:40
一文精通Java中的volatile关键字
2023-11-24 04:17:14
![](https://img.aspxhome.com/file/2023/2/59572_0s.png)
Android中扫描多媒体文件操作详解
2022-06-02 09:06:53
Android编程实现点击EditText之外的控件隐藏软键盘功能
2022-08-07 02:06:08
Android开发中Activity之间切换出现短暂黑屏的解决方法
2023-02-19 04:29:38
浅谈resultMap的用法及关联结果集映射
2022-12-25 17:42:21
![](https://img.aspxhome.com/file/2023/5/129985_0s.png)
MyBatis整合Redis实现二级缓存的示例代码
2022-02-06 15:41:24
Java模拟多线程实现抢票代码实例
2022-11-17 07:41:51
C# 并行和多线程编程——认识和使用Task
2022-03-28 05:48:04
![](https://img.aspxhome.com/file/2023/5/119495_0s.png)
Android 中SwipeRefreshLayout与ViewPager滑动事件冲突解决方法
2023-02-26 21:34:17
Android UI新组件学习和使用
2022-04-09 01:42:03
![](https://img.aspxhome.com/file/2023/7/137717_0s.png)
Struts2实现文件上传功能实例解析
2023-11-04 04:56:13
![](https://img.aspxhome.com/file/2023/6/58836_0s.png)
Android 全局Dialog的简单实现方法
2021-06-28 10:14:40