spring-redis的整合配置

Spring與Redis的整合配置:

前提:導入jar包

 <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.8.1.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>


配置文件:

redis.addr=127.0.0.1

redis.port=6379

redis.auth=root

redis.maxactive=1024

redis.maxidle=200

redis.maxwait=10000

redis.testonborrow=true


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">

    <!-- redis配置 -->
    <!--啓用redis註解-->
    <cache:annotation-driven />

    <!-- redis連接池 -->
    <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxactive}"/>
        <property name="maxIdle" value="${redis.maxidle}"/>
        <property name="maxWaitMillis" value="${redis.maxwait}"/>
        <property name="testOnBorrow" value="${redis.testonborrow}"/>
    </bean>
    <!-- redis連接工廠 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.addr}"/>
        <property name="port" value="${redis.port}"/>
        <property name="password" value="${redis.auth}"/>
        <property name="poolConfig" ref="jedisConfig"/>
    </bean>
    <!-- redis操作模板,這裏採用儘量面向對象的模板 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <!--     如果不配置Serializer,那麼存儲的時候只能使用String,如果用對象類型存儲,那麼會提示錯誤 can't cast to String!!!-->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
    </bean>

    <!--配置緩存-->
    <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg ref="redisTemplate" />
    </bean>

</beans>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章