redis与spring集成--spring-data-redis

本文介绍了如何在Spring项目中集成Spring Data Redis,并通过示例展示了如何使用RedisTemplate进行基本的Redis操作。

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

 1.需要的jar包

 

jar包方面的话,替换的时候自己测试吧,之前使用的时候自己打的一些jar包,不知怎么的死活无法连接,后来使用maven下载包的时候使用的这些,如果不清楚的话,推荐使用maven,配置依赖即可

    <dependency>  
        <groupId>org.springframework.data</groupId>  
        <artifactId>spring-data-redis</artifactId>  
        <version>1.7.1.RELEASE</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-core</artifactId>  
        <version>4.2.5.RELEASE</version>  
    </dependency>  

      
    <dependency>  
        <groupId>redis.clients</groupId>  
        <artifactId>jedis</artifactId>  
        <version>2.8.0</version>  
    </dependency> 

2.spring-application.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: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" >

	<context:property-placeholder location="classpath:redis.properties"/>

	<!-- jedis pool配置 -->
	<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<!-- 最大空闲时间 -->
		<property name="maxIdle" value="${redis.maxIdle}" />
		<!-- 最大等待毫秒数-->
		<property name="maxWaitMillis" value="${redis.maxWait}" />
		<!-- 连接有效性验证 -->
		<property name="testOnBorrow" value="${redis.testOnBorrow}" />
	</bean>
	
	<!-- redis服务器中心 -->
	<bean id="connectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<property name="poolConfig" ref="poolConfig" />
		<property name="port" value="${redis.port}" />
		<property name="hostName" value="${redis.host}" />
		<property name="password" value="${redis.password}" />
		<property name="timeout" value="${redis.timeout}"></property>
	</bean>
	
	<!-- redis客户端模板 -->
	<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
		<!-- 注入连接工厂 -->
		<property name="connectionFactory" ref="connectionFactory" />
		<!-- 配置key序列化类 -->
		<property name="keySerializer">
			<bean
				class="org.springframework.data.redis.serializer.StringRedisSerializer" />
		</property>
		<!-- 配置value序列化类 -->
		<property name="valueSerializer">
			<bean
				class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
		</property>
	</bean>

</beans>
redis.properties配置
#redis config
redis.host=127.0.0.1
redis.port=6379
redis.password=redis
redis.maxIdle=100 
redis.maxWait=1000 
redis.testOnBorrow=true 
redis.timeout=100000

3.实例代码

import java.util.Date;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import com.vclouds.redis.Bean;


public class Dao
{
	private RedisTemplate<String,Object> redisTemplate;
	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate)
	{
		this.redisTemplate = redisTemplate;
	}
	
	public Dao()
	{
		ApplicationContext app = new ClassPathXmlApplicationContext("classpath:spring-application.xml");
		System.out.println(app);
		redisTemplate = (RedisTemplate<String, Object>) app.getBean("redisTemplate");
	}
	
	@Test
	public void test(){
		new Dao();
		final Bean b = new Bean(1,"hello",new Date());
		redisTemplate.execute(new RedisCallback<Boolean>()
		{
                        /**设置string类型的key-value*/
			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException
			{
				RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
				byte[] key = serializer.serialize("hello");
				byte[] value = serializer.serialize("world");
				try
				{
					connection.set(key, value);
				} catch (Exception e)
				{
					e.printStackTrace();
					return false;
				}
				return true;
			}
			
		});
		
		String str = redisTemplate.execute(new RedisCallback<String>()
		{

			<pre name="code" class="java">    /**根据string类型的key获取value*/
                        public String doInRedis(RedisConnection connection)
                                throws DataAccessException{
                                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                                byte[] key = serializer.serialize("hello");
                                return serializer.deserialize(connection.get(key));
                        }
                 });
                 System.out.println(str);
                 }
             } 



4.常见问题

       需要注意的是这种使用方式需要将每次存放的值转换成byte数组进行操作,获取值的时候再将获取到的byte数组转为需要的类型进行操作,如果要建对象使用字符串存储,也同样需要将之转换成byte数组,但是该对象必须实现Serializable接口。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值