springboot + redis

application.yml

在spring下添加

redis:
    host: localhost
    port: 6379
    pool:
      max-idle: 8
      min-idle: 0
      max-active: 8
      max-wait: -1
    timeout: 5000
    password:
    expiration_time: 43200

Pom.xml

 <dependency>
            <groupId>org.crazycake</groupId>
            <artifactId>shiro-redis</artifactId>
            <version>2.4.2.1-RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>shiro-core</artifactId>
                    <groupId>org.apache.shiro</groupId>
                </exclusion>
            </exclusions>
        </dependency>

RedisConfig

config文件夹下建立

package com.cei.back.config;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


/**
 * <p>
 * Redis缓存配置类
 * </p>
 *
 * @author 
 * @since 
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.timeout}")
    private int timeout;
    @Value("${spring.redis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.pool.max-wait}")
    private long maxWaitMillis;

    @Bean
    public JedisPool redisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
        return jedisPool;
    }

//    //缓存管理器
//    @Bean
//    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
//        RedisCacheManager redisCacheManager = RedisCacheManager.create(connectionFactory);
//        return redisCacheManager;
//    }
//
//    @Bean
//    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
//        // 解决键、值序列化问题
//        StringRedisTemplate template = new StringRedisTemplate(factory);
//        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//        ObjectMapper om = new ObjectMapper();
//        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//        jackson2JsonRedisSerializer.setObjectMapper(om);
//        template.setValueSerializer(jackson2JsonRedisSerializer);
//        template.afterPropertiesSet();
//        return template;
//    }

}

Service

package com.cei.back.service;

import java.util.Map;

/**
 * Created by ${HeJD} on 2018/6/29.
 */
public interface RedisCacheStorage<K,V> {

    /**
     * 在redis数据库中插入 key  和value
     * @param key
     * @param value
     * @return
     */
    boolean set(K key, V value);
    /**
     * 在redis数据库中插入 key  和value 并且设置过期时间
     * @param key
     * @param value
     * @param exp 过期时间
     * @return
     */
    boolean set(K key, V value, int exp);
    /**
     * 根据key 去redis 中获取value
     * @param key
     * @return
     */
    V get(K key, Object object);
    /**
     * 删除redis库中的数据
     * @param key
     * @return
     */
    boolean remove(K key);
    /**
     * 设置哈希类型数据到redis 数据库
     * @param cacheKey 可以看做一张表
     * @param key   表字段
     * @param value
     * @return
     */
    boolean hset(String cacheKey, K key, V value);
    /**
     * 获取哈希表数据类型的值
     * @param cacheKey
     * @param key
     * @return
     */
    V hget(String cacheKey, K key, Object object);
    /**
     * 获取哈希类型的数据
     * @param cacheKey
     * @return
     */
    Map<K,V> hget(String cacheKey, Object object);
}

ServiceImpl

package com.cei.back.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.cei.back.service.RedisCacheStorage;
import com.cei.back.util.RedisUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.exceptions.JedisException;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by 
 */
@Service("redisCacheStorage")
public class RedisCacheStorageImpl<V> implements RedisCacheStorage<String, V> {

    //日志记录
    private Logger log = LoggerFactory.getLogger(RedisCacheStorageImpl.class);

    /**
     * 默认过时时间
     */
    private static final int EXPRIE_TIME = 3600 * 24;

    /**
     * 获取Jedis相关操作
     */
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean set(String key, V value) {
        return set(key, value, EXPRIE_TIME);
    }

    @Override
    public boolean set(String key, V value, int exp) {
        Jedis jedis = null;
        if (StringUtils.isEmpty(key)) {
            return false;
        }
        try {
            //获取jedis对象
            jedis = redisUtil.getResource();
            //使用对象转换为Json格式插入redis
            JSONObject json = JSONObject.fromObject(value);//将java对象转换为json对象
            String jsonValue = json.toString();//将json对象转换为json字符串
            jedis.setex(key, exp, jsonValue);


        } catch (Exception e) {
            //释放jedis对象
            redisUtil.brokenResource(jedis);
            log.info("client can't connect server");
            return false;
        } finally {
            //返还连接池
            redisUtil.returnResource(jedis);
            return true;
        }

    }

    @Override
    public V get(String key, Object object) {

        Jedis jedis = null;
        V v = null;
        if (StringUtils.isEmpty(key)) {
            log.info("redis取值,key为空");
            return null;
        }
        try {
            jedis = redisUtil.getResource();  //获取连接
            String jsonValue = jedis.get(key);   //从redis得到值,得到的是json字符串,因为我们之前插入的时候是使用的json字符串

            if (StringUtils.isEmpty(jsonValue)) {
                return null;
            }

            JSONObject obj = new JSONObject().fromObject(jsonValue);//将json字符串转换为json对象
            v = (V) JSONObject.toBean(obj, object.getClass());//将建json对象转换为你想要的java对象

            return v;
        } catch (Exception e) {
            //释放jedis对象
            if (jedis != null) {
                redisUtil.brokenResource(jedis);
            }
            log.info("client can't get value");
            return null;
        } finally {
            //返还连接池
            redisUtil.returnResource(jedis);

        }

    }

    @Override
    public boolean remove(String key) {
        Jedis jedis = null;
        try {
            jedis = redisUtil.getResource();
            if (StringUtils.isEmpty(key)) {
                log.info("redis取值,key为空");
                return false;
            }
            jedis.del(key);
        } catch (Exception e) {
            //释放jedis对象
            if (jedis != null) {
                redisUtil.brokenResource(jedis);
            }
            log.info("  del fail from redis");
            return false;

        } finally {
            //返还连接池
            redisUtil.returnResource(jedis);
            return true;
        }


    }

    @Override
    public boolean hset(String cacheKey, String key, V value) {
        Jedis jedis = null;
        //将key 和value  转换成 json 对象
        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为json字符串

        JSONObject json2 = JSONObject.fromObject(value);//将java对象转换为json对象
        String jsonValue = json2.toString();//将json对象转换为json字符串


        //操作是否成功
        boolean isSucess = true;
        if (StringUtils.isEmpty(jCacheKey)) {
            log.info("cacheKey is empty");
            return false;
        }
        try {
            jedis = redisUtil.getResource();
            //执行插入哈希
            jedis.hset(jCacheKey, key, jsonValue);
        } catch (Exception e) {
            log.info("client can't connect server");
            isSucess = false;
            if (null != jedis) {
                //释放jedis 对象
                redisUtil.brokenResource(jedis);
            }
            return false;
        } finally {
            if (isSucess) {
                //返还连接池
                redisUtil.returnResource(jedis);
            }
            return true;
        }
    }

    @Override
    public V hget(String cacheKey, String key, Object object) {
        Jedis jedis = null;
        V v = null;

        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为json字符串


        if (StringUtils.isEmpty(jCacheKey)) {
            log.info("cacheKey is empty");
            return null;
        }
        try {
            //获取客户端对象
            jedis = redisUtil.getResource();
            //执行查询
            String jsonValue = jedis.hget(jCacheKey, key);
            //判断值是否非空
            if (StringUtils.isEmpty(jsonValue)) {
                return null;
            } else {

                JSONObject obj = new JSONObject().fromObject(jsonValue);//将json字符串转换为json对象

                v = (V) JSONObject.toBean(obj, object.getClass());//将建json对象转换为java对象

            }
            //返还连接池
            redisUtil.returnResource(jedis);
        } catch (JedisException e) {
            log.info("client can't connect server");
            if (null != jedis) {
                //redisUtil 对象
                redisUtil.brokenResource(jedis);
            }
        }
        return v;
    }

    @Override
    public Map<String, V> hget(String cacheKey, Object object) {

        JSONObject json = JSONObject.fromObject(cacheKey);//将java对象转换为json对象
        String jCacheKey = json.toString();//将json对象转换为字符串
        //非空校验
        if (StringUtils.isEmpty(jCacheKey)) {
            log.info("cacheKey is empty!");
            return null;
        }
        Jedis jedis = null;
        Map<String, V> result = null;
        V v = null;
        try {
            jedis = redisUtil.getResource();
            //获取列表集合 因为插入redis的时候是jsonString格式,所以取出来key是String value也是String
            Map<String, String> map = jedis.hgetAll(jCacheKey);

            if (null != map) {
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    if (result == null) {
                        result = new HashMap<String, V>();
                    }

                    JSONObject obj = new JSONObject().fromObject(entry.getValue());//将json字符串转换为json对象
                    v = (V) JSONObject.toBean(obj, object.getClass());//将建json对象转换为java对象

                    result.put(entry.getKey(), v);
                }
            }
        } catch (JedisException e) {
            log.info("client can't connect server");
            if (null != jedis) {
                //释放jedis 对象
                redisUtil.brokenResource(jedis);
            }
        }
        return result;
    }
}

RedisUtil


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by ${HeJD} on 2018/6/29.
 */
@Component
public class RedisUtil {
    /**
     * 日志记录
     */
    private static final Logger LOG = LoggerFactory.getLogger(RedisUtil.class);
    /**
     * redis 连接池,这里jedisPool我们再之前spring配置中配置好了,交给spring管理,这里可以自动注入
     */
    @Autowired
    private JedisPool jedisPool;

    public void setPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    /**
     * 获取jedis
     *
     * @return
     */
    public Jedis getResource() {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
        } catch (Exception e) {
            LOG.info("can't  get  the redis resource");
        }
        return jedis;
    }

    /**
     * 关闭连接
     *
     * @param jedis
     */
    public void disconnect(Jedis jedis) {
        jedis.disconnect();
    }

    /**
     * 将jedis 返还连接池
     *
     * @param jedis
     */
    public void returnResource(Jedis jedis) {
        if (null != jedis) {
            try {
                jedisPool.returnResource(jedis);
            } catch (Exception e) {
                LOG.info("can't return jedis to jedisPool");
            }
        }
    }

    /**
     * 无法返还jedispool,释放jedis客户端对象,
     *
     * @param jedis
     */
    public void brokenResource(Jedis jedis) {
        if (jedis != null) {
            try {
                jedisPool.returnBrokenResource(jedis);
            } catch (Exception e) {
                LOG.info("can't release jedis Object");
            }
        }
    }
}

用例

@Resource
private RedisCacheStorage<String, Map<String, Object>> redisCacheStorage;
@Value("${spring.redis.expiration_time}")
private Integer EXPIRATION_TIME;
redisCacheStorage.set(token, MapTools.convertToMap(t_qt_user), EXPIRATION_TIME);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值