【Spring连载】使用Spring Data访问Redis(一)----快速指南

【Spring连载】使用Spring Data访问Redis(一)----快速指南

一、导入依赖

在pom.xml文件加入如下依赖就可以下载到spring data redis的jar包了:

xml 复制代码
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
		</dependency>

二、Hello World程序

首先,你需要设置一个正在运行的Redis服务器。Spring Data Redis 需要Redis 2.6或更高版本,并且Spring Data Redis集成了Lettuce和Jedis这两个流行的开源Java库。现在,你可以创建一个简单的Java应用程序,用于向Redis存储和读取值。创建要运行的主应用程序,示例如下:

java 复制代码
public class RedisApplication {

	private static final Log LOG = LogFactory.getLog(RedisApplication.class);

    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration =
                new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName("localhost");
        redisStandaloneConfiguration.setDatabase(0);
        redisStandaloneConfiguration.setPassword(RedisPassword.of("123456"));
        redisStandaloneConfiguration.setPort(6379);
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

    public static void main(String[] args) {
        JedisConnectionFactory connectionFactory = new RedisApplication().jedisConnectionFactory();
        connectionFactory.afterPropertiesSet();

        RedisTemplate<String, String> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setDefaultSerializer(StringRedisSerializer.UTF_8);
        template.afterPropertiesSet();

        template.opsForValue().set("foo", "bar");

        LOG.info("Value at foo:" + template.opsForValue().get("foo"));

        connectionFactory.destroy();
    }
}

即使在这个简单的示例中,也有一些值得注意的事情需要指出:

  • 你可以使用RedisConnectionFactory创建RedisTemplate的实例(或ReactiveRedisTemplate,用于响应式使用)。连接工厂是在支持的驱动程序之上的抽象。
  • 没有单一的方法来使用Redis,因为它支持广泛的数据结构,如plain keys("strings"),lists, sets, sorted sets, streams, hashes等等。
相关推荐
m0_547486665 小时前
《Java程序设计与实践 》全套PPT课件2026
java·开发语言
谷哥的小弟6 小时前
腾讯云服务器安装Redis Stack图文教程
服务器·redis·腾讯云·redis stack
土司大王6 小时前
LeetCode hto100——字母异位词分组
java·算法·leetcode
码匠许师傅6 小时前
【C++ 面试真题】聊聊 C++ 中的 lambda 表达式
java·c++·面试
QCodingDev6 小时前
Spring AI Alibaba ReAct Agent实战:从Tool Calling到Agent,企业AI复杂业务该如何设计?
java·人工智能·agent·ai编程·spring ai
RainCity7 小时前
Java Swing 自定义组件库分享(十六)
java·笔记·后端
NeilYuen7 小时前
【vemory】高性能KV存储AOF方案设计
linux·c++·redis·缓存
赵广陆8 小时前
企业实战:Markdown图片检索
android·java·开发语言
C++、Java和Python的菜鸟8 小时前
第3章 从0开始用若依
java·开发语言
Json____8 小时前
五金制品行业-企业官网源码
java·大数据·数据库·企业站·wwwoop.com