您的位置:首页 > 数据库 > Redis

springmvc+redis框架搭建

2016-12-24 11:35 316 查看
这是redis新增加的mxl配置,直接新建文件复制上去即可
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd ">

<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
</bean>

<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="poolConfig"/>

<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory"   ref="connectionFactory" />
</bean>

</beans>


对应的 redis.properties 这个配置,也直接复制上去即可.

redis.host=127.0.0.1

redis.port=6379

redis.pass=

maven的pom.xml配置

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.0</version>
</dependency>

我是使用此版本的jar包,其他的,我曾经试过很久,始终不能成功....希望大神来解答..

然后,这些都配置好之后,就是java代码的部分了..写个类来测试下

这是我的测试代码:

@Autowired
protected RedisTemplate<String, String> redisTemplate;

public boolean add(final String key, final String value) {
boolean resultBoolean = false;
if (redisTemplate != null) {
resultBoolean = redisTemplate.execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
RedisSerializer<String> serializer = getRedisSerializer();
byte[] keys = serializer.serialize(key);
byte[] values = serializer.serialize(value);
return connection.setNX(keys, values);
}
});
} else {
System.out.println(redisTemplate == null);
}
return resultBoolean;
}

protected RedisSerializer<String> getRedisSerializer() {
return redisTemplate.getStringSerializer();
}

这其中配置的时候,虽然看似简单,其实弄的时候,还是有过很多曲折的..建议一步一步来.可以加入我的qq群和我一起讨论.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: