小小小小涛

spring整合redis

在实际项目开发过程中会用到redis这个服务,redis是一个高效的键值对存储系统,有人也称之为非关系型数据库。其读写效率高,而且可以根据需要设置内容的存储时长,所以在web项目中很常见。

redis并不依赖spring,但是使用spring的依赖注入思想,可以很好的管理redis连接池、redis操作模板等。下面介绍如何将redis整合到spring中。除了jsdis的jar包,还需要spring-data-redis-1.0.1.RELEASE.jar(版本自定),此包提供spring对redis的支持。

xml配置文件写法基本如下:

<?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:p="http://www.springframework.org/schema/p" 
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-3.0.xsd
         ">
  
  <!-- 读取properties文件属性  --> 
  <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>
  
  <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
      <!-- 最大连接数 --> 
    <property name="maxActive" value="${redis.maxActive}" />  
    <!-- 最大空闲数 -->
    <property name="maxIdle" value="${redis.maxIdle}" /> 
    <property name="maxWait" value="${redis.maxWait}" />  
    <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
    <!-- 每次释放连接的最大数目 -->
    <property name="numTestsPerEvictionRun" value="1024" />
    <!-- 释放连接的扫描间隔(毫秒) -->
    <property name="timeBetweenEvictionRunsMillis" value="30000" />
    <!-- 连接最小空闲时间 -->
    <property name="minEvictableIdleTimeMillis" value="1800000" />
    <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
    <property name="softMinEvictableIdleTimeMillis" value="10000" />
    <!-- 在空闲时检查有效性, 默认false -->
    <property name="testWhileIdle" value="true" />
    
  </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>      
   
</beans>    

然后java代码的写法(使用注解方式)

package com.cbt.staticize.service.impl;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.cbt.staticize.service.RedisService;

@SuppressWarnings("unchecked")
@Service
public class RedisServiceImpl implements RedisService {

    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;
    
    @Override
    public void set(String key, String value) {
        try {
            ValueOperations<String, String> vop = redisTemplate
                    .opsForValue();
            vop.set(key, value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 存储指定时长
     */
    @Override
    public void set(String key, String value, Long expire) {
        try {
            ValueOperations<String, String> vop = redisTemplate
                    .opsForValue();
            vop.set(key, value);
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object get(String key) {
        Object result = null;
        ValueOperations<String, String> vop = redisTemplate
                .opsForValue();
        result = vop.get(key);
        return result;
    }

    @Override
    public boolean exist(String key) {
        return redisTemplate.hasKey(key);
    }

    @Override
    public void remove(String key) {
        if (exist(key)) {
            redisTemplate.delete(key);
        }
    }

    @Override
    public void remove(String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    @Override
    public void hset(String key, String field, String value) {
        
        HashOperations<String, String, String> hop = redisTemplate.opsForHash();
        hop.put(key, field, value);
        
    }

    @Override
    public void hset(String key, String field, String value, Long expire) {
        
        HashOperations<String, String, String> hop = redisTemplate.opsForHash();
        hop.put(key, field, value);
        redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        
    }

    @Override
    public Object hget(String key, String field) {
        
        HashOperations<String, String, String> hop = redisTemplate.opsForHash();
        return hop.get(key, field);
    }

}

至此,可直接使用redisservice操作redis。

posted on 2016-12-20 16:00  小小小小涛  阅读(234)  评论(0编辑  收藏  举报

导航