当spring和redis结合时往往都是通过配置bean来解决的首先是配置JedisPoolConfig对象,内容如下:
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxActive" value="100"/> <property name="maxIdle" value="50"/> <property name="maxWait" value="20000"/></bean>然后是配置JedisConnectionFactory对象:
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="192.168.36.131"/> <property name="port" value="6379"/> <property name="password" value="123456"/> <property name="poolConfig" ref="poolConfig"/></bean>由于java对象是不能直接存储到redis中去的,所以需要序列化java对象,有key序列器和value序列器,在RedisTemplate对象中配置key和value:
<bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/><bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory"/> <property name="keySerializer" ref="stringRedisSerializer"/> <property name="valueSerializer" ref="jdkSerializationRedisSerializer"/></bean>通过上述的配置呢就可以操作redis数据库了,下面是简单测试连接的一段代码
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); RedisTemplate redisTemplate=(RedisTemplate) applicationContext.getBean("redisTemplate"); // redisTemplate.opsForValue().set("role1","zhangsan"); SessionCallback sessionCallback=new SessionCallback() {//采用sessioncallback主要是因为set和get操作时他们有可能访问的不是一个redis连接,而通过sessioncallback接口来调用他们呢就可以只用一个redis连接 @Override public Object execute(RedisOperations redisOperations) throws DataAccessException { redisOperations.opsForValue().set("role2","lisi"); return redisOperations.opsForValue().get("role2"); } }; String aa=redisTemplate.execute(sessionCallback).toString(); System.out.println(aa);
时间: 2024-10-19 21:02:07