springboot使用redisRepository和redistemplate操作redis的过程解析
导入依赖
菜单大部分情况下不会出现变化,我们可以将其放入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;
@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
@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;
}
}
到此这篇关于springboot使用redisRepository和redistemplate操作redis的过程解析的文章就介绍到这了,更多相关springboot整合redis内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
相关文章