標籤:set 串連 jedis throw new max lis for 資料庫
當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);
Spring中redis的配置及初級操作