当前位置:   article > 正文

springboot redis存读数据_cursor> hasnext 一直为true

cursor> hasnext 一直为true

引入依赖:

maven:

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-redis</artifactId>
  4. <version>1.4.7.RELEASE</version>
  5. </dependency>

gradle:

  1. implementation 'org.springframework.data:spring-data-redis'
  2. implementation 'redis.clients:jedis'

直接使用:

  1. @Autowired
  2. private StringRedisTemplate stringRedisTemplate;

从redis读取数据:

private HashMap<String ,String> getRedisMap(String template){

        HashMap<String ,String> map = new HashMap<>();

        try {

            Cursor<Map.Entry<Object,Object>> cursor = stringRedisTemplate.opsForHash().scan(template,ScanOptions.NONE);

            Map.Entry<Object,Object> entry;

            while (cursor.hasNext()){

                entry = cursor.next();

                if(entry==null || entry.getKey()==null || entry.getValue()==null){

                    continue;

                }

                map.put(entry.getKey().toString(),entry.getValue().toString());

            }

            cursor.close();

        }catch (Exception e){

            LOGGER.error("获取redis数据异常",e);

        }

        return map;

}

 

向redis 存入数据:

long timeout =300;

        stringRedisTemplate.executePipelined(new SessionCallback<Object>() {

            @Override

            public Object execute(RedisOperations ro) {

                String userIndex;

                BoundHashOperations<String,String,String> hashOps = stringRedisTemplate.boundHashOps(templateKey);

                for(User user: userList){

                    if(user.getPos()==null){

                        continue;

                    }

                    userIndex = user.getIndex();

                    hashOps.put("name"+userIndex, Optional.ofNullable(user.getName()).orElse(""));

                    hashOps.put("age"+userIndex, String.valueOf(Optional.ofNullable(user.getAge ()).orElse(999)));

                }

//设置过期

                stringRedisTemplate.expire(templateKey, timeout, TimeUnit.SECONDS);

                return null;

            }

        }

        );

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/715818
推荐阅读
相关标签
  

闽ICP备14008679号