redis的通用类以及key生产规则的一种方式

环境 springboot1.59+redis

pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.xuxu</groupId>
    <artifactId>miaosha</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>miaosha</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <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>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>      
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置文件application.properties

#redis
redis.host=192.168.25.222
redis.port=6379
redis.timeout=3
#redis.password=123456
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3


redis配置对象读取properties配置文件中的配置

package com.xuxu.redis;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author Administrator
 * @create 2019/3/6
 */
@Component
@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;//秒

   //此处省略get set方法
}

spring中注入jedisPoll工厂用于获取jedis对象

package com.xuxu.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author Administrator
 * @create 2019/3/6
 */
@Service
public class RedisPoolFactory {
    @Autowired
    private RedisConfig redisConfig;
    @Bean
    public JedisPool jedisPool(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait()*1000);
        jedisPoolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
        return new JedisPool(jedisPoolConfig,redisConfig.getHost(),redisConfig.getPort(),
                redisConfig.getTimeout()*1000,redisConfig.getPassword(),0);
    }
}

定义一个接口KeyPrefix 定义了获取key的前缀和存活时间的方法

package com.xuxu.redis;

public interface KeyPrefix {

    /*
    获取存活时间
     */
    int expireSeconds();

    /*
    获取前缀
     */
    String getPrefix();
}

创建抽象类BasePrefix实现KeyPrefix接口

package com.xuxu.redis;

/**
 * @author Administrator
 * @create 2019/3/7
 */
public abstract class BasePrefix implements KeyPrefix {
    private int expireSeconds;
    private String prefix;

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

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

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

    @Override
    public String getPrefix() {
        //对应不同的对象key前缀,比如要以用户ID标识为前缀 为key 前缀为UserKey:id+指定的key
        //这样针对不同的模块例如部门也想要以部门ID标识为前缀为key 前缀为DeptKey:id+指定的key
        //避免全部都是id+key这种形式
        String className = getClass().getSimpleName();
        return className+":"+prefix;
    }
}

定义子类UserKey相当于User模块的key前缀

package com.xuxu.redis;

/**
 * @author Administrator
 * @create 2019/3/7
 */
public class UserKey extends BasePrefix {

    public UserKey(String prefix) {
        super(prefix);
    }

    public static UserKey getByID = new UserKey("id");
    public static UserKey getByIName= new UserKey("name");
}

定义子类DeptKey相当于Dept模块的key前缀

package com.xuxu.redis;

/**
 * @author Administrator
 * @create 2019/3/7
 */
public class DeptKey extends BasePrefix {

    public DeptKey(String prefix) {
        super(prefix);
    }

    public static DeptKey getByID = new DeptKey("id");
    public static DeptKey getByIName= new DeptKey("name");
}

操作redis工具类

package com.xuxu.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;

/**
 * @author Administrator
 * @create 2019/3/6
 */
@Service
public class RedisService {
    @Autowired
    private JedisPool jedisPool;

    /**
     * 根据key获取值
     *
     * @param keyPrefix 前缀对象
     * @param key       key
     * @param clazz     值类型
     * @param <T>
     * @return              value
     */
    public <T> T get(KeyPrefix keyPrefix, String key, Class<T> clazz) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //真实键名
            String realKey = keyPrefix.getPrefix() + key;
            String str = jedis.get(realKey);
            T t = stringToBean(str, clazz);
            return t;
        } finally {
            jedisReturn(jedis);
        }
    }

    /**
     * 设置key-value
     * @param keyPrefix 前缀对象
     * @param key           key
     * @param value         value
     * @param <T>
     * @return                  是否设置成功
     */
    public <T> boolean set(KeyPrefix keyPrefix, String key, T value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String valueStr = beanToString(value);
            if (StringUtils.isEmpty(valueStr)) {
                return false;
            }
            //真实键名
            String realKey = keyPrefix.getPrefix() + key;
            //有效时间
            int expireSeconds = keyPrefix.expireSeconds();
            if ( expireSeconds<= 0) {   //永久生效
                jedis.set(realKey, valueStr);
            } else {
                jedis.setex(realKey, expireSeconds, valueStr); //设置有效时间
            }
            return true;
        } finally {
            jedisReturn(jedis);
        }
    }

    /**
     *  判断指定键是否存在
     * @param keyPrefix
     * @param key
     * @return
     */
    public boolean exists(KeyPrefix keyPrefix, String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //真实键名
            String realKey = keyPrefix.getPrefix() + key;
            return jedis.exists(realKey);
        }finally {
            jedisReturn(jedis);
        }
    }

    /**
     * 对指定key的数值加1
     * @param keyPrefix
     * @param key
     * @return
     */
    public Long incr(KeyPrefix keyPrefix, String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //真实键名
            String realKey = keyPrefix.getPrefix() + key;
            return jedis.incr(realKey);
        }finally {
            jedisReturn(jedis);
        }
    }

    /**
     * 对指定key的数值减1
     * @param keyPrefix
     * @param key
     * @return
     */
    public Long decr(KeyPrefix keyPrefix, String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            //真实键名
            String realKey = keyPrefix.getPrefix() + key;
            return jedis.decr(realKey);
        }finally {
            jedisReturn(jedis);
        }
    }
    /**
     *  将jedis连接对象返回连接池
     * @param jedis
     */
    private void jedisReturn(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }
    /**
     *
     * @param value 从对象转换成字符串
     * @param <T>
     * @return
     */
    private <T> String beanToString(T value) {
        if (value == null) {
            return null;
        } else if (value.getClass() == int.class || value.getClass() == Integer.class) {
            return String.valueOf(value);
        } else if (value.getClass() == String.class) {
            return (String) value;
        } else if(value.getClass()==Long.class || value.getClass()==long.class){
            return String.valueOf(value);
        }else {
            return JSON.toJSONString(value);
        }
    }

    /**
     * 从字符串转换成对象
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    private <T> T stringToBean(String str, Class<T> clazz) {
        if (StringUtils.isEmpty(str)) {
            return null;
        } else if (clazz == int.class || clazz == Integer.class) {
            return (T) Integer.valueOf(str);
        } else if (clazz == String.class) {
            return (T) str;
        } else if (clazz == long.class || clazz == Long.class) {
            return (T) Long.valueOf(str);
        } else {
            return JSON.toJavaObject(JSON.parseObject(str), clazz);
        }
    }




}

返回码和信息

package com.xuxu.result;

/**
 * @author Administrator
 * @create 2019/3/5
 */
public class CodeMsg {
    private int code;
    private String msg;
    //通用异常
    public static CodeMsg SUCCESS= new CodeMsg(0,"success");
    public static  CodeMsg SERVER_ERROR=new CodeMsg(500100,"服务端异常");

    public CodeMsg(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

 //省略get set方法
}

返回结果类

package com.xuxu.result;

/**
 * @author Administrator
 * @create 2019/3/4
 */
public class Result<T> {
    private int code;
    private String msg;
    private T data;

    public static <T>Result<T> success(T data){
        return new Result(data);
    }

    public static <T>Result<T> error(CodeMsg cm){
        return new Result(cm);
    }

    public Result( T data) {
        this.code=0;
        this.msg = "success";
        this.data = data;
    }

    public Result(CodeMsg cm){
        if(cm!=null){
            this.code=cm.getCode();
            this.msg=cm.getMsg();
        }
        return ;
    }
   //省略get set方法
}

测试类

package com.xuxu.controller;

import com.xuxu.domain.User;
import com.xuxu.redis.RedisService;
import com.xuxu.redis.UserKey;
import com.xuxu.result.CodeMsg;
import com.xuxu.result.Result;
import com.xuxu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Administrator
 * @create 2019/3/5
 */
@Controller
@RequestMapping("/test")
public class Test {
   
    @Autowired
    private RedisService redisService;
    
    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<String> redisGet(){
        String value = redisService.get(UserKey.getByID,"1",String.class);
        return Result.success(value);
    }

    @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet(){
        boolean value = redisService.set(UserKey.getByID,"1","test");
        return Result.success(value);
    }
}

redis中生产的key值为

此时如果需要给部门模块设置key

将测试类set方法改为

  @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet(){
        boolean value = redisService.set(DeptKey.getByID,"1","test");
        return Result.success(value);
    }

这样就很好的区分了不同模块相同功能的key值

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值