服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - springboot使用redisRepository和redistemplate操作redis的过程解析

springboot使用redisRepository和redistemplate操作redis的过程解析

2023-02-07 13:54march of Time Java教程

本文给大家介绍springboot整合redis/分别用redisRepository和redistemplate操作redis,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

导入依赖

菜单大部分情况下不会出现变化,我们可以将其放入Redis 加快加载速度

?
1
2
3
4
5
6
7
8
9
<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>

基本配置

?
1
2
3
4
5
6
7
8
9
10
11
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 通过用户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以及模板

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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:

?
1
2
3
4
5
@Repository
public interface StuRepository extends CrudRepository<stu,String> {
stu findByName(String name);
//自定义查询方法,使用了@Indexed的name属性查询
}

调用:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_41358574/article/details/118087940

延伸 · 阅读

精彩推荐