我们以将字典数据写入Redis中,并查询数据为例
@Resource
private TestMapper testMapper;
@Resource
ShardingRedisUtil shardingRedisUtil;
@Override
public void testSetRedis() {
// 获取所有字典信息
List list = testMapper.selectAll();
// 根据字典类型分组
Map> distMap = list.stream()
.collect(Collectors.groupingBy(TbSysDictInfo::getTypeCode));
// 将数据写入redis
shardingRedisUtil.hMSet(Dictconstants.DICT_RESULT, distMap);
}
Dictconstants方法
public class Dictconstants {
/**
* 字典结果属性
*/
public static final String DICT_RESULT = "dict_result_";
}
@Override
public List testGetRedis(String type) {
// 根据字典类型获取列表
Map> distMap = shardingRedisUtil.hMGet(new TypeReference>() {
}, Dictconstants.DICT_RESULT, type);
if (distMap.get(type)!=null){
return distMap.get(type);
}else {
return new ArrayList<>();
}
}
这个工具类功能很强大,大家可以自行挖掘
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@Component
public class ShardingRedisUtil {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
private RedisTemplate redisTemplate;
private static final int SHARDING_COUNT = 100; //分片数
private static final int SCAN_COUNT = 1000; //扫描分批数
private ObjectMapper objectMapper = new ObjectMapper();
public void hMSet(String key, Map map) {
hMSet(key, map, SHARDING_COUNT);
}
public Map hMGet(TypeReference typeReference, String key, String... field) {
return hMGet(typeReference, SHARDING_COUNT, key, field);
}
public Map hMGet(TypeReference typeReference, String key, List fields) {
if (CollectionUtils.isEmpty(fields)) {
return null;
}
return hMGet(typeReference, key, fields.toArray(new String[1]));
}
public long hDel(String key, String... field) {
return hDel(SHARDING_COUNT, key, field);
}
public void hMSet(String key, Map map, int shardingCount) {
if (!CollectionUtils.isEmpty(map)) {
Map> tmpMap = new HashMap<>();
for (Map.Entry entry : map.entrySet()) {
String tmpKey = entry.getKey();
Object tmpValue = entry.getValue();
int num = Math.abs(tmpKey.hashCode() % shardingCount);
String hashKey = String.format("%s$%s", key, num);
tmpMap.computeIfAbsent(hashKey, k -> new HashMap<>()).put(tmpKey, tmpValue);
}
for (Map.Entry> entry : tmpMap.entrySet()) {
redisTemplate.opsForHash().putAll(entry.getKey(), entry.getValue());
}
}
}
public void hMSetToOneGroup(String key, Map map) {
if (!CollectionUtils.isEmpty(map)) {
redisTemplate.opsForHash().putAll(key, map);
}
}
public Map hMGetfromOneGroup(TypeReference typeReference, String key, String... field) {
Map resultMap = new HashMap<>();
if (field != null) {
List
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@ConditionalOnProperty(name = "spring.redis.host")
public class RedisConfiguration {
@Value("${spring.redis.host}")
private String host ;
@Value("${spring.redis.port}")
private int port ;
@Value("${spring.redis.password}")
private String password ;
@Value("${spring.redis.timeout:3000}")
private int timeout ;
@Value("${redis.jedisPoolConfig.maxActive:300}")
private int maxActive ;
@Value("${redis.jedisPoolConfig.maxIdle:100}")
private int maxIdle ;
@Value("${redis.jedisPoolConfig.minIdle:1}")
private int minIdle ;
@Value("${redis.jedisPoolConfig.maxWait:5000}")
private int maxWait ;
@Value("${spring.redis.database:0}")
private int database;
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringRedisSerializer);
redisTemplate.setHashKeySerializer(stringRedisSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public JedisPool JedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWaitMillis( maxWait);
JedisPool jedisPool = new JedisPool(poolConfig,host,port,timeout,password,database);
return jedisPool;
}
}
spring:
redis:
host: localhost
port: 6379
#password: