首页 > 其他分享 >springBoot项目中常用工具类

springBoot项目中常用工具类

时间:2023-03-18 17:13:06浏览次数:36  
标签:return springBoot 项目 param public key 常用工具 final String

springBoot项目中常用工具类

目录

一、RedisUtils

  • 导入依赖
 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  • 配置类
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }


}
  • 工具类
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value)
    {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key 缓存的键值
     * @param value 缓存的值
     * @param timeout 时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit)
    {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout)
    {
        return expire(key, timeout, TimeUnit.SECONDS);
    }

    /**
     * 设置有效时间
     *
     * @param key Redis键
     * @param timeout 超时时间
     * @param unit 时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit)
    {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 获取有效时间
     *
     * @param key Redis键
     * @return 有效时间
     */
    public long getExpire(final String key)
    {
        return redisTemplate.getExpire(key);
    }

    /**
     * 判断 key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public Boolean hasKey(String key)
    {
        return redisTemplate.hasKey(key);
    }

    /**
     * 获得缓存的基本对象。
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key)
    {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个对象
     *
     * @param key
     */
    public boolean deleteObject(final String key)
    {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     *
     * @param collection 多个对象
     * @return
     */
    public boolean deleteObject(final Collection collection)
    {
        return redisTemplate.delete(collection) > 0;
    }

    /**
     * 缓存List数据
     *
     * @param key 缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> long setCacheList(final String key, final List<T> dataList)
    {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key)
    {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     *
     * @param key 缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet)
    {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext())
        {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     *
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key)
    {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap)
    {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     *
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key)
    {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value)
    {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 获取Hash中的数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey)
    {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     *
     * @param key Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys)
    {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 删除Hash中的某条数据
     *
     * @param key Redis键
     * @param hKey Hash键
     * @return 是否成功
     */
    public boolean deleteCacheMapValue(final String key, final String hKey)
    {
        return redisTemplate.opsForHash().delete(key, hKey) > 0;
    }

    /**
     * 获得缓存的基本对象列表
     *
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern)
    {
        return redisTemplate.keys(pattern);
    }

}

二、JwtUtil

  • 导入依赖
<!-- jwt -->
<dependency>
     <groupId>io.jsonwebtoken</groupId>
     <artifactId>jjwt</artifactId>
     <version>0.9.1</version>
</dependency>
  • 配置文件
jwt:
  header: Authorization
  expire: 604800
  secret: f4402f4b1c984955a4a22c7c43614ba3
  • 工具类
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtil {

    private String header;
    private String secret;
    private long expire;

    /**
     * 生成token
     * @param str
     * @return
     */
    public String generateToken(String str){
        Date now = new Date();
        //失效时间
        Date expireDate = new Date(now.getTime() + 1000 * expire);
        return Jwts.builder()
                .setHeaderParam("typ","jwt")
                .setSubject(str)
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();
    }

    /**
     * 解析token
     * @param jwt
     * @return
     */
    public Claims getClaimsByToken(String jwt){
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        }catch (Exception e){
            return null;
        }
    }

    /**
     * 判断jwt是否过期
     * @param claims
     * @return
     */
    public boolean jwtExpire(Claims claims){
        return claims.getExpiration().before(new Date());
    }

}

三、Result

  • 统一返回结果类
@Data
public class Result implements Serializable {

    private int code;
    private String msg;
    private Object data;

    public static Result success(Object data) {
        return success(200, "操作成功", data);
    }

    public static Result fail(String msg) {
        return fail(400, msg, null);
    }

    public static Result success (int code, String msg, Object data) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }

    public static Result fail (int code, String msg, Object data) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }

}

标签:return,springBoot,项目,param,public,key,常用工具,final,String
From: https://www.cnblogs.com/cxfbk/p/17231203.html

相关文章

  • 玩转SpringBoot原理:掌握核心技术,成为高级开发者
    本文通过编写一个自定义starter来学习springboot的底层原理,帮助我们更好的使用springboot集成第三方插件步骤一:创建项目步骤二:添加依赖步骤三:创建自动配置类步骤四:创......
  • 项目管理的问题
    目标管理时间管理进度管理资源管理质量管理沟通管理:我的诉求,对方的问题,一起解决问题。风险管理:推动团队放入合适的资源在疑难点以及突发问题制度管理采购管理绩......
  • docker 常用工具
    windows下常常需要linux环境直接安装虚拟机不方便也浪费资源所以直接在docker下安装一个centos然后搭建好开发环境就是个不错的办法一、Linux环境1、安装centos(默......
  • 一个基于微服务架构的SpringBoot+vue2.0的在线教育系统【源码开源】【强烈建议收藏】
    今天给大家开源一个基于springboot+vue2.0的微服务在线教育平台系统,系统是攀登网的孟哥和汉远哥开发的,我进行了本版本的开发。该系统完全免费、开源。为防止刷着刷者找不......
  • Springboot 核心注解的作用
    SpringBoot是一个非常流行的Java开发框架,它采用注解的方式来简化应用程序的开发和配置。在SpringBoot中,核心注解是一组用于控制和配置应用程序的注解。本文将介绍这......
  • 使用python爬虫爬取链家潍坊市二手房项目
    使用python爬虫爬取链家潍坊市二手房项目需求分析需要将潍坊市各县市区页面所展示的二手房信息按要求爬取下来,同时保存到本地。流程设计明确目标网站URL(https://wf.l......
  • SpringBoot使用redisTemplate存入Redis中Key会出现乱码
    测试操作Redis把key数据存入Redis,然后通过key取出UserMapper对象。@TestpublicvoidredisCacheTest(){Stringkey=UUID.randomUUID().toString();......
  • 【网络工程】9、实操-万达酒店综合项目(三)
    接上篇《​​8、实操-万达酒店综合项目(三)​​》之前我们按照项目要求进行模拟拓扑的构建实操,完成了办公区部分的网络配置,本篇我们来继续完成其他区域的网络配置。一、总体......
  • spring boot 新建项目
    由于springboot项目,不管是java工程还是web工程都可以直接以jar方式运行,所以推荐创建jar工程,这里创建jar工程项目为例。二:两种方式创建springboot项目1.第一种方式手动在......
  • SpringBoot——自定义自动配置与起步依赖
    SpringBoot——自定义自动配置与起步依赖SpringBoot为我们提供了灵活强大的自动配置与起步依赖功能,接下来我们参考其实现原理,实现专属于我们自己的自动配置与起步依赖。......