spring整合redis

来源:互联网 发布:中美南海对峙 知乎 编辑:程序博客网 时间:2024/06/05 10:39

pom.xml

<dependency>      <groupId>org.springframework.data</groupId>      <artifactId>spring-data-redis</artifactId>      <version>1.6.0.RELEASE</version>  </dependency>  <dependency>      <groupId>redis.clients</groupId>      <artifactId>jedis</artifactId>      <version>2.7.3</version>  </dependency>
spring.xml 中redis配置

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans.xsd"       default-lazy-init="false">    <!-- jedis pool配置 -->    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">        <property name="minIdle" value="${redis.minIdle}"/>        <property name="maxIdle" value="${redis.maxIdle}"/>        <property name="maxTotal" value="${redis.maxTotal}"/>        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>    </bean>    <!-- spring data redis JedisConnectionFactory-->    <bean id="redisSentinelConfiguration" class="org.springframework.data.redis.connection.RedisSentinelConfiguration">        <property name="master">            <bean class="org.springframework.data.redis.connection.RedisNode">                <property name="name" value="${redis.clusterName}"/>            </bean>        </property>        <property name="sentinels">            <set>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg index="0" value="${redis1.host}"/>                    <constructor-arg index="1" value="${redis1.port}"/>                </bean>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg index="0" value="${redis2.host}"/>                    <constructor-arg index="1" value="${redis2.port}"/>                </bean>                <bean class="org.springframework.data.redis.connection.RedisNode">                    <constructor-arg index="0" value="${redis3.host}"/>                    <constructor-arg index="1" value="${redis3.port}"/>                </bean>            </set>        </property>    </bean>    <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">        <constructor-arg ref="redisSentinelConfiguration"/>        <property name="poolConfig" ref="jedisPoolConfig"/>    </bean>    <bean id="stringRedisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">        <property name="connectionFactory" ref="jedisConnFactory"/>    </bean></beans>
redis.properties
#Redis config redis.minIdle=100redis.maxIdle=100redis.maxTotal=300redis.testOnBorrow=trueredis1.host=redis1.port=6379redis2.host=redis2.port=6379redis3.host=redis3.port=6379redis.clusterName=
redis 工具类

import com.alibaba.fastjson.JSONObject;import com.baofoo.pt.manager.cpt.outer.RedisManager;import org.apache.commons.lang3.StringUtils;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.dao.DataAccessException;import org.springframework.data.redis.connection.RedisConnection;import org.springframework.data.redis.core.RedisCallback;import org.springframework.data.redis.core.StringRedisTemplate;import lombok.extern.slf4j.Slf4j;import org.springframework.stereotype.Service;import java.util.*;@Service@Slf4jpublic class RedisUtil{    @Autowired    private StringRedisTemplate redisTemplate;    public boolean insertObject(final Object obj, final String key, final long timeout) {        Long start=System.currentTimeMillis();        try {            final String value = JSONObject.toJSONString(obj);            boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {                @Override                public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {                    byte[] redisKey = redisTemplate.getStringSerializer().serialize(key);                    byte[] redisValue = redisTemplate.getStringSerializer().serialize(value);                    if (timeout > 0){                        redisConnection.setEx(redisKey, timeout, redisValue);                    }else {                        redisConnection.set(redisKey, redisValue);                    }                    return true;                }            });            log.info("insertObject key:{},result:{} 耗时:{}", key,result,System.currentTimeMillis()-start);            return result;        } catch (Exception e){            log.error("insertObject异常,key:{} 耗时:{} 异常:{}",key,System.currentTimeMillis()-start, e);        }        return false;    }    public String queryObjectByKey(final String key) {        try {            Long start =System.currentTimeMillis();            String resultStr = redisTemplate.execute(new RedisCallback<String>() {                @Override                public String doInRedis(RedisConnection redisConnection) throws DataAccessException {                    byte[] redisKey = redisTemplate.getStringSerializer().serialize(key);                    if (redisConnection.exists(redisKey)){                        byte[] value = redisConnection.get(redisKey);                        return redisTemplate.getStringSerializer().deserialize(value);                    }                    return null;                }            });            log.info("queryObjectByKey(key), key:{} value:{} 耗时:{}", key, resultStr,System.currentTimeMillis()-start);            return resultStr;        } catch (Exception e){            log.error("queryObjectByKey(key), key:{} 异常:{}", key, e);        }        return null;    }    public <T> T queryObjectByKey(String key, Class<T> clazz) {        try {            String resultStr = queryObjectByKey(key);            if (StringUtils.isBlank(resultStr)){                return null;            }            T value = JSONObject.parseObject(resultStr, clazz);            return value;        } catch (Exception e){            log.error("queryObjectByKey(key,clazz),key:{} 异常:{}", key, e);        }        return null;    }    public <T> List<T> queryListByKey(String key, Class<T> clazz) {        try {            String resultStr = queryObjectByKey(key);            if (StringUtils.isBlank(resultStr))                return null;            List<T> value = JSONObject.parseArray(resultStr, clazz);            log.info("queryListByKey key:{} result:{}",key, value==null?0:value.size());            return value;        } catch (Exception e){            log.error("queryListByKey(key,clazz),key:{} 异常:{}",key, e);        }        return null;    }    public boolean insertIntoMap(final String key, final String field, Object value) {        try {            final String keyValue = JSONObject.toJSONString(value);            boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {                @Override                public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {                    byte[] redisKey = redisTemplate.getStringSerializer().serialize(key);                    byte[] fieldKey = redisTemplate.getStringSerializer().serialize(field);                    byte[] fieldValue = redisTemplate.getStringSerializer().serialize(keyValue);                    return redisConnection.hSet(redisKey, fieldKey,fieldValue);                }            });            log.info("insertMap key:{} field:{} result:{} ",key,field,result);            return result;        } catch (Exception e){            log.error("insertIntoMap redis出现异常:{} key:{},field:{}",key,field,e);        }        return false;    }    public <T> Map<String,T> getMapAll(final String key ,final Class<T> clazz) {        try {            Map<String,T> result = redisTemplate.execute(new RedisCallback<Map<String,T>>() {                @Override                public Map<String,T> doInRedis(RedisConnection redisConnection) throws DataAccessException {                    byte[] redisKey = redisTemplate.getStringSerializer().serialize(key);                    Map<byte[], byte[]>  map = redisConnection.hGetAll(redisKey);                    if(map !=null && map.size() > 0){                        Map<String,T> result = new HashMap<String, T>();                        for (byte[] b: map.keySet()){                            String resultKey = redisTemplate.getStringSerializer().deserialize(b);                            T resultValue = JSONObject.parseObject(redisTemplate.getStringSerializer().deserialize(map.get(b)), clazz);                            result.put(resultKey, resultValue);                        }                        return result;                    }                    return null;                }            });            log.info("getMapAll key:{} size:{}", key, result==null?0:result.size());            return result;        } catch (Exception e){            log.error("getMapAll redis出现异常,key:{} 异常:{}",key, e);        }        return null;    }    public boolean deleteObject(final String key) {        try {            Long result = redisTemplate.execute(new RedisCallback<Long>() {                @Override                public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {                    byte[] redisKey = redisTemplate.getStringSerializer().serialize(key);                    return redisConnection.del(redisKey);                }            });            log.info("deleteObject key:{} result:{}", key,result);            return result > 0;        } catch (Exception e){            log.error("删除redis指定key出现异常:{}", e);        }        return false;    }}







原创粉丝点击