使用SpringDataRedis的入門

在使用ssm框架下,咱們會到redis作緩存。

1> 第一步,導包。

<!-- Redis客戶端 -->  
<dependency>  
    <groupId>redis.clients</groupId>   
    <artifactId>jedis</artifactId>  
    <version>2.9.0</version>  
</dependency>  
<!-- redis Spring 基於註解配置 -->   
<dependency>    
  <groupId>org.springframework.data</groupId>    
  <artifactId>spring-data-redis</artifactId>    
  <version>1.7.2.RELEASE</version>    
</dependency>

2> 第二步,建立redis的配置文件。

redis.properties

#redis地址
        redis.host=127.0.0.1 
        #端口
        redis.port=6379 
        # 密碼,沒有則能夠不寫
        redis.pass=123456 
        redis.database=0 
        redis.maxIdle=300 
        redis.maxWait=3000 
        redis.testOnBorrow=true

spring-redis.xml,可是建議直接寫在applicationContext.xml(也就是spring的配置文件,在web.xml中已經配置了的)中,這樣就能夠直接引用.

若是是新建了一個xml文件,就要在spring配置文件中引入,或者在web.xml中配置。

<!-- 加載redis配置文件,能夠後面用,爲了簡單我用得默認配置 -->  
       <context:property-placeholder location="classpath:/redis/redis-config.properties"/>  
  
       <bean id="jedisFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"/>  
  
       <!-- 操做模板 -->  
       <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
              <property name="connectionFactory" ref="jedisFactory"/>  
              <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>

幾個小插曲
1.在xml中引用外部xml文件web

<import resource="spring-redis.xml"/> spring-redis.xml就是外部文件

2.解決一個xml中只能引入一個.properties文件的問題
在引用的時候,用以下寫法
redis

<context:property-placeholder ignore-unresolvable="true" location="classpath:first.properties" />
<context:property-placeholder ignore-unresolvable="true" location="classpath:second.properties" />

3. redis中要存入對象時,對象要實現Serializable接口spring

相關文章
相關標籤/搜索