要基于配置文件spring整合redis,首先需要確保你已經添加了spring-data-redis依賴。然后,你需要進行以下步驟來實現整合:
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="100"/>
<property name="maxIdle" value="50"/>
<property name="minIdle" value="10"/>
<property name="testOnBorrow" value="true"/>
<property name="testOnReturn" value="true"/>
<property name="testWhileIdle" value="true"/>
<property name="timeBetweenEvictionRunsMillis" value="30000"/>
<property name="numTestsPerEvictionRun" value="10"/>
<property name="minEvictableIdleTimeMillis" value="60000"/>
</bean>
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="localhost"/>
<property name="port" value="6379"/>
<property name="password" value="your_password_here"/>
<property name="poolConfig" ref="jedisPoolConfig"/>
</bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory"/>
<property name="keySerializer" ref="stringRedisSerializer"/>
<property name="valueSerializer" ref="stringRedisSerializer"/>
</bean>
<bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
請根據你的實際情況修改"hostName"、"port"和"password"的值。
<import resource="classpath:redis-config.xml"/>
@Autowired
private RedisTemplate<String, String> redisTemplate;
public void setValue(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
以上代碼演示了如何使用redisTemplate設置和獲取redis中的鍵值對。
這樣,你就可以基于配置文件spring整合redis了。