Spring和spring boot整合redis

spring 整合

包和版本的依赖关系很严重

我的配置

spring-data-redis-1.6.6.RELEASE.jar

spring-tx-4.2.5.RELEASE.jar

redis-2.7.2.jar

commons-pool2-2.4.3.jar

aopalliance-1.0.jar

redis服务端 是4.2.11 目前没测 和redis服务端交互式有什么异常

springboot (v2.3.9.RELEASE) 整合

pom配置

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- redis依赖 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.2</version>
        </dependency>

配置类

package com.ag.dtools.config;

import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    /**
     * 注入 RedisConnectionFactory
     */
    @Autowired
    RedisConnectionFactory factory;

    /**
     * 实例化 RedisTemplate 对象
     *
     * @return
     */
    @Bean("redisTemplate")
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
        redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setValueSerializer(fastJsonRedisSerializer);
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

    /**
     * 实例化 HashOperations 对象,可以使用 Hash 类型操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }

    /**
     * 实例化 ValueOperations 对象,可以使用 String 操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }

    /**
     * 实例化 ListOperations 对象,可以使用 List 操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }

    /**
     * 实例化 SetOperations 对象,可以使用 Set 操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }

    /**
     * 实例化 ZSetOperations 对象,可以使用 ZSet 操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
}

工具类

package com.ag.dtools.utils;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import org.apache.flink.table.runtime.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtil {
    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    private static final String LOCK_SUCCESS = "OK";

    private static final Long SUCCESS = 1L;

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    private ValueOperations<String, String> valueOperations;

    @PostConstruct
    public void init(){
        valueOperations = stringRedisTemplate.opsForValue();
        logger.info("-------------Redis 初始化成功");
    }

    /**  默认过期时长,单位:秒 */
    public final static long                DEFAULT_EXPIRE = 60 * 60 * 24;

    /**  不设置过期时长 */
    public final static long                NOT_EXPIRE     = -1;

    /**
     * 插入缓存默认时间
     * @param key 键
     * @param value 值
     */
    public Boolean set(String key, Object value)
    {
        return set(key, value, DEFAULT_EXPIRE);
    }

    /**
     * 插入缓存
     * @param key 键
     * @param value 值
     * @param expire 过期时间(s)
     */
    public Boolean set(String key, Object value, long expire)
    {


        stringRedisTemplate.opsForValue();
        valueOperations.set(key,      JSONUtil.toJsonStr(value));
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    /**
     * 返回字符串结果
     * @param key 键
     * @return
     */
    public String get(String key)
    {
        return valueOperations.get(key);
    }

    /**
     * 返回符合条件的键
     * @param keyPattern 键
     * @return
     */
    public Collection<String> listKeys(String keyPattern){
        return stringRedisTemplate.keys(keyPattern);
    }

    /**
     * 返回指定类型结果
     * @param key 键
     * @param clazz 类型class
     * @return
     */
    public <T> T get(String key, Class<T> clazz)
    {
        String value = valueOperations.get(key);
        return value == null ? null : JSONUtil.toBean(value, clazz);
    }

    /**
     * 删除缓存
     * @param key 键
     */
    public void delete(String key)
    {
        redisTemplate.delete(key);
    }

    /**
     * 删除缓存
     * @param keys 键集合
     */
    public void deleteAll(Collection<String> keys)
    {
        redisTemplate.delete(keys);
    }

    /**
     * 加锁,无阻塞
     *
     * @param
     * @param
     * @return
     */
    public  Boolean tryLock( String key, String value, long expireTime) {
        try {
            //SET命令返回OK ,则证明获取锁成功
            Boolean ret = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.MINUTES);
            return ret;
        } catch (Exception e) {
            logger.info("Redis加锁出现异常{}",e);
            return false;
        }
    }


    /**
     * 解锁
     *
     * @param key
     * @return
     */
    public  Boolean unlock(String key) {
        try {
            Object result = redisTemplate.delete(Collections.singletonList(key));
            if (SUCCESS.equals(result)) {
                return true;
            }
        } catch (Exception e) {
            logger.info("Redis解锁出现异常{}",e);
            return false;
        }
        return false;
    }

}

控制类


public class RedisController {


    Logger logger = LoggerFactory.getLogger(RedisController.class);
    @Resource
    private RedisUtil redisUtil;

    @RequestMapping(value = "/test-redis")
    public boolean testRedis(){
        LogEntity logEntity = new LogEntity();
        logEntity.setUuid("123456");
        logEntity.setProjectName("redis项目测试");
        return redisUtil.set(logEntity.getUuid(),logEntity);
    }

}

参考

https://www.jianshu.com/p/b9154316227e

posted @ 2018-12-13 18:06  方东信  阅读(658)  评论(0编辑  收藏  举报