在springboot中封装一个自己的redis模板

新建一个springboot项目

引入依赖

注意引入的不是 spring-boot-starter-data-redis这个依赖

这里有一个坑,必须引入spring-boot-configuration-processor这个依赖,不然配置文件里面的值不能读取出来

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
         <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.38</version>
        </dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
	<optional>true</optional>
</dependency>

配置文件

#redis 这个是我们自定义的属性
redis.host=192.168.220.128
redis.port=6379
redis.timeout=3
redis.password=123456
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3

新建一个配置文件类读取类

来读取我们在application.properties中自定义的属性

package com.example.miaosha_xdp.redis;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Getter
@Setter
@Component
/**
 * 这个注解让我们可以读取到配置文件中所有以redis开头到属性值
 */
@ConfigurationProperties(prefix = "redis")
public class RedisConfig {
    private String host;
    private int port;
    private int timeout;//秒
    private String password;
    private int poolMaxTotal;
    private int poolMaxIdle;
    private int poolMaxWait;//秒
}

新建RedisPoolFactory类

这个用来加载配置文件类并得到一个redis到连接池

package com.example.miaosha_xdp.service;

import com.example.miaosha_xdp.redis.RedisConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
public class RedisPoolFactory {
    @Autowired
    RedisConfig redisConfig;

    /**
     * @Bean这个注解将JedisPool注入到Spring容器中
     */
    @Bean
    public JedisPool JedisPoolFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
        jedisPoolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
        jedisPoolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);

        return new JedisPool(jedisPoolConfig, redisConfig.getHost(), redisConfig.getPort(),
                redisConfig.getTimeout() * 1000, redisConfig.getPassword(), 0);
        //上面参数中的0是redis总共有16个库,我们从0库开始
    }

}

使用模板工厂来生成key的前缀

我们有一个需要,要求不同的类存入reids必须加上一个响应的前缀,下面来实现 :

模板接口

/**
 * 模板接口
 */
public interface KeyPrefix {
    /**
     * 设置超时时间
     * @return
     */
    int expireSeconds();

    /**
     * 获取key的前缀
     * @return
     */
    String getPrefix();
}

模板抽象类

package com.example.miaosha_xdp.redis;
/**
 * 定义为抽象类,为了不让直接使用,而是作为模板让别的类继承
 */
public abstract class BasePrefix implements KeyPrefix {
    private int expireSeconds;

    private String prefix;

    public BasePrefix(String prefix) {
        //0表示永久有效
        this(0,prefix);
    }

    public BasePrefix(int expireSeconds, String prefix) {
        this.expireSeconds = expireSeconds;
        this.prefix = prefix;
    }

    @Override
    public int expireSeconds() {
        return expireSeconds;
    }

    @Override
    public String getPrefix() {
        String className = prefix.getClass().getSimpleName();
        return className+":"+prefix;
    }
}

实现抽象类具体的子类

package com.example.miaosha_xdp.redis;

public class UserKey extends BasePrefix {

    public UserKey(String prefix) {
        super(prefix);
    }
    public static UserKey getId=new UserKey("id");
    public static UserKey getName=new UserKey("name");
}

 

package com.example.miaosha_xdp.redis;

public class OrderKey  extends BasePrefix {

    public OrderKey(int expireSeconds, String prefix) {
        super(expireSeconds, prefix);
    }
}

 

package com.example.miaosha_xdp.redis;

public class MiaoshaUserKey extends BasePrefix {
    public static final int TOKEN_EXPIRE = 3600 * 24 * 2;

    public MiaoshaUserKey(int expireSeconds, String prefix) {
        super(expireSeconds, prefix);
    };
    public static MiaoshaUserKey token=new MiaoshaUserKey(TOKEN_EXPIRE,"token");
}

编写我们的封装类

package com.example.miaosha_xdp.redis;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Service
public class RedisService {
    @Autowired
    private JedisPool jedisPool;

    /**
     * 获取单个key值
     * @param keyPrefix
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T get(KeyPrefix keyPrefix,String key,Class<T> clazz){
        Jedis  jedis=null;
        try {
            Jedis poolResource = jedisPool.getResource();
            String realKey = keyPrefix.getPrefix() + key;
            String stringValue = poolResource.get(realKey);
            T t=stringToBean(stringValue,clazz);
            return t;
        }finally {
            returnToPool(jedis);
        }

    }

    /**
     * 存入对象
     * @param keyPrefix
     * @param key
     * @param value
     * @param <T>
     * @return
     */
    public <T> boolean set(KeyPrefix keyPrefix,String key,T value){
        Jedis  jedis=null;
        try {
            Jedis poolResource = jedisPool.getResource();
            String str=beanToString(value);
            if (StringUtils.isEmpty(str)){
                return false;
            }
            String realKey  = keyPrefix.getPrefix() + key;
            int seconds =  keyPrefix.expireSeconds();
            if(seconds <= 0) {
                jedis.set(realKey, str);
            }else {
                jedis.setex(realKey, seconds, str);
            }
            return true;
        }finally {
            returnToPool(jedis);
        }

    }
    /**
     * 判断key是否存在
     * */
    public <T> boolean exists(KeyPrefix prefix, String key) {
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            //生成真正的key
            String realKey  = prefix.getPrefix() + key;
            return  jedis.exists(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    /**
     * 增加值
     * */
    public <T> Long incr(KeyPrefix prefix, String key) {
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            //生成真正的key
            String realKey  = prefix.getPrefix() + key;
            return  jedis.incr(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    /**
     * 减少值
     * */
    public <T> Long decr(KeyPrefix prefix, String key) {
        Jedis jedis = null;
        try {
            jedis =  jedisPool.getResource();
            //生成真正的key
            String realKey  = prefix.getPrefix() + key;
            return  jedis.decr(realKey);
        }finally {
            returnToPool(jedis);
        }
    }

    private <T> String beanToString(T value) {
        if(value == null) {
            return null;
        }
        Class<?> clazz = value.getClass();
        if(clazz == int.class || clazz == Integer.class) {
            return ""+value;
        }else if(clazz == String.class) {
            return (String)value;
        }else if(clazz == long.class || clazz == Long.class) {
            return ""+value;
        }else {
            return JSON.toJSONString(value);
        }
    }

    private <T> T stringToBean(String stringValue, Class<T> clazz) {
        if (StringUtils.isEmpty(stringValue)||clazz==null){
            return null;
        }
        if (clazz==int.class||clazz==Integer.class){
            return (T) Integer.valueOf(stringValue);
        }
        if (clazz==String.class){
            return (T) stringValue;
        }
        if (clazz==long.class||clazz==Long.class){
            return (T) Long.valueOf(stringValue);
        }
        return JSON.toJavaObject(JSON.parseObject(stringValue),clazz);
    }

    private void returnToPool(Jedis jedis) {
        if (jedis!=null){
            jedis.close();
        }
    }
}

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值