springmvc+redis框架搭建

来源:互联网 发布:网络营销策划的要素 编辑:程序博客网 时间:2024/05/22 01:42
这是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代码的部分了..写个类来测试下

这是我的测试代码:

@Autowiredprotected 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群和我一起讨论.



0 0
原创粉丝点击