redis在spring框架中的使用

来源:互联网 发布:测量图片尺寸软件 编辑:程序博客网 时间:2024/04/30 16:34

redis的客户端实现我选择的是jedis

spring框架中包含了对redis的支持,其实是一层封装,使得我们可以使用样板来简化代码,也可以选择不使用spring提供的样板,自己在jedis基础上做封装

使用spring的项目可以很容易就将redis功能添加进来,作为系统的缓存


redis服务端是单独部署的,spring中配置的是redis的客户端,使得spring项目可以访问到redis服务器

首先是包的引入,

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

spring的部分配置,不同的jedis版本,参数也发生了变化,尤其需要注意根据不同的版本使用对应的参数命名

<context:property-placeholder location="classpath:redis.properties" />      <context:component-scan base-package="com.x.redis.dao">    </context:component-scan>    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">          <property name="maxIdle" value="${redis.maxIdle}" />          <property name="maxActive" value="${redis.maxActive}" />          <property name="maxWait" value="${redis.maxWait}" />          <property name="testOnBorrow" value="${redis.testOnBorrow}" />      </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>

最后一个bean redisTemplate
通过注入的方式在程序中使用
@Autowiredprotected RedisTemplate<Serializable, Serializable> redisTemplate;


0 0