本章节将介绍怎样在 Spring 应用中引入 Spring Data Redis,且使用它操作 Redis NoSQL 数据库。项目结构图如下:
在 pom.xml 中添加如下依赖:
<!-- spring data redis 的依赖 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.3.6.RELEASE</version> </dependency> <!-- jedis 依赖(redis 的 java 驱动) --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> </dependency>
在 main/resources 目录中创建 application-context.xml 配置文件,内容如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- 配置 Redis 连接工厂 --> <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:use-pool="true"/> <!-- 配置 Redis 序列化 --> <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> <!-- 配置 Redis 模板对象,设置 key 和 value 的序列化为字符串 --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:keySerializer-ref="stringRedisSerializer" p:valueSerializer-ref="stringRedisSerializer" p:connection-factory-ref="jedisConnFactory"/> </beans>
下面创建一个拥有 main 方法的简单类,测试使用 RedisTemplate 添加和获取字符串,代码如下:
package com.hxstrive.redis; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; /** * 第一个 Spring Data Redis 程序 * @author hxstrive.com 2022/8/3 */ public class HelloWorld { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( "application-context.xml"); System.out.println("context = " + context); // 获取 Redis 模板 RedisTemplate<String,String> template = context.getBean(RedisTemplate.class); System.out.println("template = " + template); // 写入数据 ValueOperations<String,String> ops = template.opsForValue(); ops.set("spring-redis", "Hi! Redis"); // 获取数据 String value = ops.get("spring-redis"); System.out.println(value); } }
运行上面程序,输出如下:
log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. context = org.springframework.context.support.ClassPathXmlApplicationContext@20fa23c1, started on Wed Aug 03 13:43:10 CST 2022 template = org.springframework.data.redis.core.RedisTemplate@1bb5a082 Hi! Redis Process finished with exit code 0