学无先后,达者为师

网站首页 编程语言 正文

idea 导入Redis Spring Data Redis使用方式

作者:宗渡 更新时间: 2024-03-06 编程语言

操作步骤:

一:导入Spring Data Redis 的maven坐标

我们要在Springboot项目中的pom依赖文件中引入Redis的maven坐标。

​
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
  </dependency>

​

然后刷新maven,自动引入依赖所需要的jar包。

二:配置Redis数据源

一般我们都在resources中的yml文件中进行数据源配置,例如mybytis中mysql中的配置

  redis:
    host: ${sky.redis.host}
    port: ${sky.redis.port}
    password: ${sky.redis.password}
    database: ${sky.redis.database}

因为要方便数据的管理,我们要将实际数据放在-dev.yml文件当中

  redis:
    host: localhost
    port: 6379
    password: 123456
    database: 0

三:编写配置类,创建RedisTemplate对象

在配置包中添加RedisConfiguration类

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {
    //返回值是Redis模板对象
    //注入Redis连接工厂对象
    @Bean //按照类型将RedisConnectionFactory注入进来
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        log.info("开始创建redis模板对象");
        RedisTemplate redisTemplate = new RedisTemplate();
        //关联RedisConnectionFactory  设置redis的连接工厂对象
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置redis key的序列化器 字符串类型的
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return  redisTemplate;
    }


}

四:通过RedsTemplate对象操作Redis

我们在test测试包中添加一个测试类操作Redis

注入RedisTemplate对象 因为我们在编写配置类,创建RedisTemplate对象中添加了@Bean注解

交给了Spring管理,产生这个Bean对象的方法Spring只会调用一次,随后Spring将会将这个Bean对象放在自己的IOC容器中。

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;

@SpringBootTest
public class SpringDateRedisTest {
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedisTemplate(){


        System.out.println(redisTemplate);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //可以操作字符串类型的数据
        HashOperations hashOperations = redisTemplate.opsForHash();
        //list集合
        ListOperations listOperations = redisTemplate.opsForList();
        //set集合
        SetOperations setOperations = redisTemplate.opsForSet();
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
    }
}

编译并运行

运行结果为这个表示RedisTemplate对象注入成功!!

感谢大佬们的观看,有什么不足的欢迎评论区和私信留言,谢谢大家的关注和点赞收藏,我会持续更新的!!

原文链接:https://blog.csdn.net/dhsjdh124/article/details/136439716

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新