使用Redis管道机制Pipeline批量操作

@Component
public class redispipe {

    @Autowired
    RedisTemplate redisTemplate;
    
    StringRedisSerializer serialize = new StringRedisSerializer();

	@Scheduled(fixedDelay = 1000 * 60)
    private void make(){
        List<UserEntity> userList = new ArrayList<>(); //模拟数据
        executePipeline(userList);
    }
    
    private void executePipeline(List<UserEntity> list){
        redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                list.forEach(item->{
                    String key = item.getName();
                    String value = item.getAge();
                    //进行redis操作
                    redisConnection.set(key.getBytes(),value.getBytes());
                    //或者
                    redisConnection.set(serialize.serialize(key),serialize.serialize(value));
                    
                    //也可以使用下面这种,但是不推荐,会加多个双引号  如原本是 【张三:18】 存到redis会变 【"张三":"18"】 不方便get
                    redisConnection.set(redisTemplate.getKeySerializer().serialize(key)
                            ,redisTemplate.getKeySerializer().serialize(value));
                });
                return null;
            }
        });
    }
}

你可能感兴趣的:(redis,redis,缓存,java)