spring boot StringRedisTemplate redis Hash操作

版权声明:杨杨杨~~的版权 https://blog.csdn.net/weixin_38316697/article/details/88868196

spring boot StringRedisTemplate redis Hash操作

准备工作:添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

以下是相关代码:

    @Autowired
    private  StringRedisTemplate stringRedisTemplate;


    @ApiOperation(value = "redis  Hash存值",notes = "将数据保存到redis hash")
    @ResponseBody
    @PostMapping("/setHash")
    public ResponseBo setHash(@RequestBody RedisHashModel redisHashModel) {
        try{
           Map<String,String> map = new HashMap<>();
           map.put(redisHashModel.getKey(),redisHashModel.getValue());
            stringRedisTemplate.opsForHash().putAll(redisHashModel.getName(),map);
            return ResponseBo.ok();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("保存失败" + e.getMessage());
        }
    }

    @ApiOperation(value = "获取 hash redis 精准查询")
    @ResponseBody
    @CrossOrigin(origins = "*")
    @PostMapping("/selectHashVaule")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Hash_key",value = "redis hash key + '___' redis key",required = false,dataType = "String"),
    })
    public ResponseBo selectHashVaule( @RequestBody String Hash_key){
        Object o =null;
        try{
             o = stringRedisTemplate.opsForHash().get(Hash_key.split("___")[0], Hash_key.split("___")[1]);
        }catch (Exception e){
            e.printStackTrace();
            return  ResponseBo.error("查询失败");
        }
        return ResponseBo.ok(o);
    }


    @ApiOperation(value = "redis  删除Hash",notes = "删除redis hash")
    @GetMapping("/deleteHash/{key}")
    public ResponseBo deleteHash(@PathVariable  String key) {
        try{

            stringRedisTemplate.delete(key);
            return ResponseBo.ok();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseBo.error("保存失败" + e.getMessage());
        }
    }


    @ApiOperation(value = "redis获取hash",notes = "获取redis中的hash")
    @GetMapping("/getHash/{key}")
    public ResponseBo getHash(@PathVariable  String key) {
        try{
            Map values = stringRedisTemplate.opsForHash().entries(key);

                System.out.println(values.toString());
            return ResponseBo.ok(values.toString());
        }catch (Exception e){
            e.printStackTrace();
        }
       return null;
    }

猜你喜欢

转载自blog.csdn.net/weixin_38316697/article/details/88868196