012_Spring Data Redis

本文详细介绍了如何使用Spring Data Redis进行Java项目集成,包括相关jar包的引入、配置application.properties、编写applicationContext.xml,以及创建User对象和RedisTest测试类,通过JUnit进行各种操作如设置、获取、删除字符串及序列化User对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Spring Data Redis简介

2. Spring Data Redis相关jar包

2.1. Spring相关jar包

 

2.2. Spring Data Redis相关jar包 

2.3. Json相关jar包 

3. Spring Data Redis案例

3.1. 新建一个名为spring-data-redis的Java项目, 同时添加相关jar包。

 

3.2. 添加Junit

3.2.1. 项目上右键——>Build Path——>Configure Build Path...

 

3.2.2. 点击Add Library... 

3.2.3. 选择JUnit——>Next——>Apply and Close 

3.2.4. JUnit能力 

3.3. 在src下新建application.properties 

spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=5
spring.redis.pool.max-total=20

spring.redis.hostName=192.168.25.138
spring.redis.port=6379
spring.redis.password=lyw123456

3.4. 在src下新建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- 配置读取properties文件的工具类 -->
	<context:property-placeholder location="classpath:application.properties"/>
	
	<!-- Jedis连接池 -->
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="${spring.redis.pool.max-total}"/>
		<property name="maxIdle" value="${spring.redis.pool.max-idle}"/>
		<property name="minIdle" value="${spring.redis.pool.min-idle}"/>
	</bean>
	
	<!-- Jedis连接工厂: 创建Jedis对象的工厂 -->
	<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<!-- IP地址 -->
		<property name="hostName" value="${spring.redis.hostName}"/>
		<!-- 端口 -->
		<property name="port" value="${spring.redis.port}"/>
		<!-- 端口 -->
		<property name="password" value="${spring.redis.password}"/>
		<!-- 连接池 -->
		<property name="poolConfig" ref="poolConfig"/>
	</bean>
	
	<!-- Redis模板对象:是SpringDataRedis提供的用户操作Redis的对象 -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<property name="connectionFactory" ref="jedisConnectionFactory"/>
		<!-- 默认的序列化器: 序列化器就是根据规则将存储的数据中的key与value做字符串的序列化处理 -->
		<!-- keySerializer、valueSerializer: 对应的是Redis中的String类型 -->
		<!-- hashKeySerializer、hashValueSerializer: 对应的是Redis中的Hash类型 -->
		<property name="keySerializer">
			<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
		</property>
		<property name="valueSerializer">
		    <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
		</property>
	</bean>
</beans>

3.5. 新建User.java

package com.bjbs.pojo;

import java.io.Serializable;

public class User implements Serializable {
	private static final long serialVersionUID = 1L;

	private Integer id;
	private String name;
	private Integer age;

	public User() {

	}

	public User(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}

3.6. 新建RedisTest.java

package com.bjbs.test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.bjbs.pojo.User;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class RedisTest {
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * 添加一个字符串
	 */
	@Test
	public void setStr(){
		redisTemplate.opsForValue().set("spring-data-redis", "SpringData Redis存储字符串");
	}
	
	/**
	 * 获取一个字符串
	 */
	@Test
	public void getStr(){
		String str = (String)redisTemplate.opsForValue().get("spring-data-redis");
		System.out.println(str);
	}
	
	/**
	 * 删除一个值
	 */
	@Test
	public void delValue(){
		redisTemplate.delete("user_json");
	}

	/**
	 * 添加User对象, 使用JDK的序列化器
	 */
	@Test
	public void setUesr() {
		User user = new User();
		user.setAge(20);
		user.setName("张三丰");
		user.setId(1);
		// 重新设置序列化器
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		redisTemplate.opsForValue().set("user", user);
	}
	
	/**
	 * 取User对象, 使用JDK的序列化器
	 */
	@Test
	public void getUser() {
		// 重新设置序列化器
		redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
		User users = (User) redisTemplate.opsForValue().get("user");
		System.out.println(users);
	}
	
	/**
	 * 基于JSON格式存User对象
	 */
	@Test
	public void setUseJSON() {
		User user = new User();
		user.setAge(20);
		user.setName("李四丰");
		user.setId(1);
		redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(User.class));
		redisTemplate.opsForValue().set("user_json", user);
	}
	
	/**
	 * 基于JSON格式取User对象
	 */
	@Test
	public void getUseJSON() {
		redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<>(User.class));
		User user = (User) this.redisTemplate.opsForValue().get("user_json");
		System.out.println(user);
	}
}

3.7. 启动服务器上的Redis, 选中setStr方法, 右键——>Run As——>JUnit Test

3.8. 选中getStr方法, 右键——>Run As——>JUnit Test 

3.9. 选中setUser方法, 右键——>Run As——>JUnit Test 

3.10. 选中getUser方法, 右键——>Run As——>JUnit Test

 3.11. 选中setUserJSON方法, 右键——>Run As——>JUnit Test 

3.12. 选中getUserJSON方法, 右键——>Run As——>JUnit Test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值