上一章我们整合好了mybatis-Plus 这一章我们引入一些项目要用到的一些组件redis、rabbitMq
1. common工程引入redis
首先,需要引入redis的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
如果使用lettuce 还需要引入
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
引入完依赖以后我们还需要定义一个redis配置类,添加到common工程下的config目录,
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;
/**
* @ClassName: RedisConfig
* @Description:
* @Author: songWenHao
* @Date: 2022/5/30 13:36
*/
@Configuration
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
RedisTemplate<String, Object> 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的工具类,添加到conmon工程下的utils目录
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;
/**
* @ClassName: RedisCacheUtil
* @Description:
* @Author: songWenHao
* @Date: 2022/5/30 13:38
*/
@Slf4j
@Component
public class RedisCacheUtil {
@Autowired
private RedisTemplate<String, String> 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<String> 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<String> 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<String> hashGet(String key, List<String> 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<String, String> hashEntries(String key) {
try {
HashOperations<String, String, String> 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<String, String> 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<String, String> 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<String> 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依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
需要创建一个配置类用来声明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;
/**
* @ClassName: RabbitMqBeanConfig
* @Description: 用于声明rabbitmq相关的bean
* @Author: songWenHao
* @Date: 2022/6/1 16:23
*/
@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.RabbitMqBeanConfig
rabbitMq具体的使用我们在后面具体写使用代码的时候在讲解包括redis也是。
本文介绍了如何在Spring Boot项目中整合Redis和RabbitMQ。首先,通过添加相关依赖并配置Redis,创建了RedisTemplate及Redis工具类,用于实现数据的增删查改操作。接着,引入RabbitMq依赖,并配置了RabbitMq的Bean。文章最后提到这两个组件在实际项目中的应用场景,如Redis用于管理token,RabbitMq则用于消息传递。
459

被折叠的 条评论
为什么被折叠?



