栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springBoot项目搭建包含RBAC模块 -- 引入redis和rabbitMq(三)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springBoot项目搭建包含RBAC模块 -- 引入redis和rabbitMq(三)

上一章我们整合好了mybatis-Plus 这一章我们引入一些项目要用到的一些组件redis、rabbitMq

1. 引入redis

首先,需要引入redis的依赖


  org.springframework.boot
  spring-boot-starter-data-redis

如果使用lettuce 还需要引入


    org.apache.commons
    commons-pool2

引入完依赖以后我们还需要定义一个redis配置类,

package com.swh.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {

        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);

        // 用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer); // key
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定要序列化的域(field,get,set),访问修饰符(public,private,protected)
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); //value

        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

我自己封装了一个redis的工具类 

package com.swh.common.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Component
public class RedisCacheUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public String stringGet(String key) {
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis string get 异常:{}", e.getMessage());
            return null;
        }
    }

    public List stringGet(String... key) {
        try {
            return redisTemplate.opsForValue().multiGet(Arrays.asList(key));
        } catch (Exception e) {
            for (String s : key) {
                if (ObjectUtil.isNull(s) || StrUtil.equalsAnyIgnoreCase(s, "null") || StrUtil.isBlank(s)) {
                    LOGGER.error("存在为空值的key");
                    e.printStackTrace();
                }
            }
            LOGGER.error("redis string get 异常:{}", e.getMessage());
            return null;
        }
    }

    public void stringDel(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis string get 异常:{}", e.getMessage());
        }
    }

    public void stringPut(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis string set 异常:{}", e.getMessage());
        }
    }

    public void stringPut(String key, String value, int i, TimeUnit timeUnit) {
        try {
            redisTemplate.opsForValue().set(key, value, i, timeUnit);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis string set 异常:{}", e.getMessage());
        }
    }

    public String hashGet(String key, String mapKey) {
        try {
            return (String) redisTemplate.opsForHash().get(key, mapKey);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis hash get 异常:{}", e.getMessage());
            return null;
        }
    }

    public List hashGet(String key, String... mapKeys) {
        try {
            return Arrays.stream(mapKeys).map(k -> {
                Object o = redisTemplate.opsForHash().get(key, k);
                if (ObjectUtil.isNotNull(o)) {
                    return (String) o;
                } else {
                    LOGGER.error("redis Hash 取出值为空:一级key{},二级key{}", key, k);
                    return null;
                }
            }).filter(Objects::nonNull).collect(Collectors.toList());
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis hash get 异常:{}", e.getMessage());
            return new ArrayList<>();
        }
    }

    public List hashGet(String key, List hashKeys) {
        try {
            return hashKeys.parallelStream().map(k -> {
                Object o = redisTemplate.opsForHash().get(key, k);
                if (ObjectUtil.isNotNull(o)) {
                    return (String) o;
                } else {
                    LOGGER.debug("redis Hash 取出值为空:一级key{},二级key{}", key, k);
                    return null;
                }
            }).filter(Objects::nonNull).collect(Collectors.toList());
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis hash entries 异常:{}", e.getMessage());
            return new ArrayList<>();
        }
    }

    public Map hashEntries(String key) {
        try {
            HashOperations hashOperations = redisTemplate.opsForHash();
            return hashOperations.entries(key);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis hash entries 异常:{}", e.getMessage());
            return new HashMap<>();
        }
    }

    public void hashPut(String key, String mapKey, String value) {
        try {
            redisTemplate.opsForHash().put(key, mapKey, value);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("redis hash put 异常:{}", e.getMessage());
        }
    }

    public void hashPut(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("redis hash putAll 异常:{}", e.getMessage());
        }
    }

    public void hashPut(String key, Map map, int i, TimeUnit timeUnit) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (i > 0) {
                redisTemplate.expire(key, i, timeUnit);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("redis hash putAll 异常:{}", e.getMessage());
        }
    }

    public void hashPut(String key, String mapKey, String value, int i, TimeUnit timeUnit) {
        try {
            redisTemplate.opsForHash().put(key, mapKey, value);
            if (i > 0) {
                redisTemplate.expire(key, i, timeUnit);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("redis hash put 异常:{}", e.getMessage());
        }
    }

    public void hashDel(String key, Object... mapKeys) {
        try {
            redisTemplate.opsForHash().delete(key, mapKeys);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis hash delete 异常:{}", e.getMessage());
        }
    }

    public long getExpire(String key) {
        try {
            return redisTemplate.getExpire(key);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("redis getExpire 异常:{}", e.getMessage());
            return -1;
        }
    }

    public void setExpire(String key, long time, TimeUnit timeUnit) {
        try {
            if (time > 0){
                redisTemplate.expire(key, time, timeUnit);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("redis setExpire 异常:{}", e.getMessage());
        }
    }

    public void setToAdd(String key, String value) {
        try {
            redisTemplate.opsForSet().add(key, value);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis set add  异常:{}", e.getMessage());
        }
    }

    public void setToRemove(String key, String value) {
        try {
            redisTemplate.opsForSet().remove(key, value);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis set remove  异常:{}", e.getMessage());
        }
    }

    public Set setForMembers(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            if (ObjectUtil.isNull(key) || StrUtil.equalsAnyIgnoreCase(key, "null") || StrUtil.isBlank(key)) {
                LOGGER.error("存在为空值的key");
                e.printStackTrace();
            }
            LOGGER.error("redis set members  异常:{}", e.getMessage());
            return new HashSet<>();
        }
    }

    public Long getIncr(String key) {
        return new RedisAtomicLong(key, Objects.requireNonNull(redisTemplate.getConnectionFactory())).getAndIncrement();
    }

    public void setIncr(String key, int value) {
        redisTemplate.opsForValue().set(key, value + 1 + "");
    }


}

在application.yml添加你的redis链接配置就可以使用了

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

项目中redis我是来管理token的,当然你也可以用来缓存其他的数据,毕竟redis的效率还是很高的。

2. 引入rabbitMq

首先,引入rabbitMq依赖 


   org.springframework.boot
   spring-boot-starter-amqp

需要创建一个配置类用来声明rabbitMq相应的bean

package com.swh.common.config;

import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static com.swh.common.constant.AdminUserConst.Mqkey.MQ_SCAN_MENU_RESOURCE;
import static com.swh.common.constant.AdminUserConst.Mqkey.QUEUE_MQ_ADD_EER_LOG;



@Configuration
public class RabbitMqBeanConfig {

    @Bean
    public Queue scanMenuResource() {
        return new Queue(MQ_TEST);
    }


}

这个类需要加载到自动装备中,在resources目录下创建一个META-INF目录然后创建一个spring.factories 文件把对应的配置类路径加进去,这里还有之前的一些需要添加的配置类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=
  com.swh.common.config.RedisConfig,
  com.swh.common.utils.RedisCacheUtil,
  com.swh.common.config.RabbitMqBeanConfig,
  com.swh.common.config.MybatisPlusConfig,

rabbitMq具体的使用我们在后面具体写使用代码的时候在讲解包括redis也是。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/984237.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号