spring data redis使用

maven工程導入座標

        <!-- redis nosql 內存數據庫 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${jedis.version}</version>
        </dependency>

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

applicationContext配置

<!-- jedis 連接池配置 -->
     <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
        <property name="maxIdle" value="300" />        
        <property name="maxWaitMillis" value="3000" />  
        <property name="testOnBorrow" value="true" />  
    </bean>  

    <!-- jedis 連接工廠 -->
    <bean id="redisConnectionFactory"  
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
        p:host-name="localhost" p:port="6379" p:pool-config-ref="poolConfig"  
        p:database="0" />  

    <!-- spring data 提供 redis模板  -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory" ref="redisConnectionFactory" /> 
        <!-- 如果不指定 Serializer   -->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"> 
            </bean>
        </property> 
    </bean>  

Spring自動注入RedisTemplate

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

將鍵值對保存到redis,設置保存時間

    redisTemplate.opsForValue().set(key,value, 24,TimeUnit.HOURS);

用key將鍵值對刪除

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