SpringBoot项目集成Redis

pom

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: password

RedisUtil 工具类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplateBean;

    private static RedisTemplate<Object, Object> redisTemplate;

    @SuppressWarnings("static-access")
    @PostConstruct
    public void init() {
        redisTemplate = redisTemplateBean;
    }

    public static void save(final String key, Object value) {
        saveWithExpir(key, value, 0);
    }

    public static <T> T get(final String key) {
        return get(key, false);
    }

    public static void saveWithExpir(final String key, Object value, final long expirtime) {
        final byte[] vbytes = SerializeUtil.serialize(value);
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            byte[] kbytes = redisTemplate.getStringSerializer().serialize(key);
            connection.set(kbytes, vbytes);
            if (expirtime > 0) {
                connection.expire(kbytes, expirtime);
            }
            return null;
        });
    }

    public static void saveWithExpir(final String key, Object value) {
        final byte[] vbytes = SerializeUtil.serialize(value);
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            byte[] kbytes = redisTemplate.getStringSerializer().serialize(key);
            connection.set(kbytes, vbytes);
            return null;
        });
    }

    /**
     * 返回自增的key值
     *
     * @param key
     * @return
     * @date 2017年7月3日 下午3:49:26
     */
    public static <T> T getIncrKey(final String key) {
        final byte[] incrbytes = redisTemplate.getStringSerializer().serialize(key);
        return redisTemplate.execute((RedisCallback<T>) connection -> {
            Long key1 = connection.incr(incrbytes);
            return (T) key1;
        });
    }

    /**
     * 获取
     *
     * @param key
     * @return
     */
    public static <T> T get(final String key, final boolean delete) {
        return redisTemplate.execute((RedisCallback<T>) connection -> {
            byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
            if (connection.exists(keybytes)) {
                byte[] valuebytes = connection.get(keybytes);
                T value = (T) SerializeUtil.unserialize(valuebytes);
                if (delete) {
                    connection.del(keybytes);
                }
                return value;
            }
            return null;
        });
    }

    /**
     * 存值
     *
     * @param key
     * @param value
     * @return
     */
    public static boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("redis set error:{}", e.getMessage(), e);
            return false;

        }

    }

    /**
     * 存值并设置过期时间
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public static boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error("redis set error:{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 批量获取
     *
     * @param keys
     * @return
     */
    public static <T> T batchGet(final List<String> keys) {
        return redisTemplate.execute((RedisCallback<T>) connection -> {
            byte[][] byteKeys = new byte[keys.size()][128];
            for (int index = 0; index < keys.size(); ++index) {
                byteKeys[index] = redisTemplate.getStringSerializer().serialize(keys.get(index));
            }
            List<byte[]> byteValus = connection.mGet(byteKeys);
            List<T> result = new ArrayList<>();
            for (byte[] byteValue : byteValus) {
                T value = null;
                if (null != byteValue) {
                    value = (T) SerializeUtil.unserialize(byteValue);
                }
                result.add(value);
            }
            return (T) result;
        });
    }

    /**
     * 删除
     *
     * @param key
     * @return
     */
    public static void delete(final String key) {
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
            connection.del(keybytes);
            return null;
        });
    }

    public static Long getKeyTtl(final String key) {
        return redisTemplate.execute((RedisCallback<Long>) connection -> {
            byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
            return connection.ttl(keybytes);
        });
    }

    public static void setExpir(final String key, final long expirtime) {
        redisTemplate.execute((RedisCallback<Object>) connection -> {
            byte[] keybytes = redisTemplate.getStringSerializer().serialize(key);
            connection.expire(keybytes, expirtime);
            return null;
        });
    }

    public static String getMapValue(final String key, final String hashKey) {
        String value = (String) redisTemplate.opsForHash().get(key, hashKey);
        return value;
    }

    public static void setMapValue(final String key, final String hashKey, final String value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
    }

}

SerializeUtil

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {

	/**
	 * 序列化
	 * 
	 * @param object
	 * @return<update
	 */
	public static byte[] serialize(Object object) {
		ObjectOutputStream oos = null;
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeObject(object);
			return baos.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	/**
	 * 反序列化
	 * 
	 * @param bytes
	 * @return
	 */
	public static Object unserialize(byte[] bytes) {
		ByteArrayInputStream bais = null;
		try {
			bais = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘水水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值