【Redis-高效的NoSQL数据库】SpringBoot整合SpringDataRedis操作redis

Redis-高效的NoSQL数据库之SpringBoot整合SpringDataRedis操作redis



前言

Spring Data是Spring公司的顶级项目,里面包含了N多个二级子项目,这些子项目都是相对独立的项目。每个子项目是对不同API的封装。
所有Spring Boot整合Spring Data xxxx的启动器都叫做spring-boot-starter-data-xxxx
Spring Data 好处是方便操作对象类型。
把Redis不同值的类型放到一个opsForXXX方法中。

  • opsForValue : String值
  • opsForList : 列表List
  • opsForHash: 哈希表Hash
  • opsForZSet: 有序集合Sorted Set
  • opsForSet : 集合

一、添加依赖

代码如下(示例):

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
</dependencies>

二、配置文件

  • spring.redis.host=localhost 默认值
  • spring.redis.port=6379 端口号默认值

代码如下(示例):

spring:
  redis:
    host: 192.168.52.133
  cluster:
  nodes: 192.168.93.10:7001,192.168.93.10:7002,192.168.93.10:7003,192.168.93.10:7004,192.168.93.10:7005,192.168.93.10:7006

三、编写配置类

代码如下(示例):

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory 		  factory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
        return redisTemplate;
    }
}

四、编写代码

1. 编写对象新增

代码如下(示例):

@Autowired
private RedisTemplate<String, Object> redisTemplate;

@Test
public void testString() {
    People peo = new People(1, "李强");
    redisTemplate.opsForValue().set("people", peo);
}

2. 编写List

代码如下(示例):

@Test
public void testList() {
    List<People> list = new ArrayList<>();
    list.add(new People(1, "李强"));
    list.add(new People(2, "王三妹"));
    redisTemplate.opsForValue().set("peoList", list);
}

3. 编写List取值

代码如下(示例):

@Test
public void testGetList(){
    redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<List>(List.class));
    List<People> peoList= (List<People>) redisTemplate.opsForValue().get("peoList");
    System.out.println(peoList);
}
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值