【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等等。
相关推荐
Re_zero2 小时前
线上日志被清空?这段仅10行的 IO 代码里竟然藏着3个毒瘤
java·后端
洋洋技术笔记2 小时前
Spring Boot条件注解详解
java·spring boot
程序员清风20 小时前
程序员兼职必看:靠谱软件外包平台挑选指南与避坑清单!
java·后端·面试
皮皮林55121 小时前
利用闲置 Mac 从零部署 OpenClaw 教程 !
java
NE_STOP1 天前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
华仔啊1 天前
挖到了 1 个 Java 小特性:var,用完就回不去了
java·后端
SimonKing1 天前
SpringBoot整合秘笈:让Mybatis用上Calcite,实现统一SQL查询
java·后端·程序员
日月云棠2 天前
各版本JDK对比:JDK 25 特性详解
java
用户8307196840822 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
JavaGuide2 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code