redis整合进spring项目,需要在项目中添加以下jar包
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>
org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.3.0.RELEASE</version>
</dependency>
项目中的redis作为客户端,需要一个配置文件对访问redis服务端进行配置,和数据库数据源配置类似,可以使用properties文件填写配置项:
#=============Redis===============
redis.host = 127.0.0.1
redis.port = 6379
redis.maxTotal = 300
redis.maxIdle = 100
redis.maxWaitMillis = 1000
redis.testOnBorrow = true
redis.pass =
redis.timeout = 100000
redis.default.db = 0
这些配置项和连接池的配置类似,不再赘述。既然要将redis与spring相整合,就需要在spring配置文件中配置需要托管的类:
<!-- jedis pool配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- spring data redis -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="usePool" value="true"></property>
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<!--
<property name="password" value="${redis.pass}" />
-->
<property name="timeout" value="${redis.timeout}" />
<property name="database" value="${redis.default.db}"></property>
<constructor-arg index="0" ref="jedisPoolConfig" />
</bean>
<bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
<property name="connectionFactory" ref="jedisConnectionFactory" />
</bean>
项目中使用了字符串做缓存所以配置了stringRedisTemplate,通过spring注入 stringRedisTemplate:
@Resource
protected StringRedisTemplate stringRedisTemplate;
写入:
stringRedisTemplate.opsForValue().set(key, JsonString);
读出:
stringRedisTemplate.opsForValue().get(key);