AllBlu

导航

redis设置

 1. redis设置、获取、删除数据

package com.guard.crowd.handler;

import com.guard.crowd.entity.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class RedisRemoteHandler {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/redis/set/key/value/remote")
    public ResultEntity<String> setKeyValue(@RequestParam("key") String key, @RequestParam("value") String value) {
        try {
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key, value);
        } catch (Exception e) {
            ResultEntity.failed(e.getMessage());
        }
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/redis/set/key/value/with/timeout/remote")
    public ResultEntity<String> setKeyValueWithTimeout(
            @RequestParam("key") String key,
            @RequestParam("value") String value,
            @RequestParam("timeUnit") TimeUnit timeUnit,
            @RequestParam("time") Integer time
    ) {
        try {
            ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key, value, time, timeUnit);
        } catch (Exception e) {
            ResultEntity.failed(e.getMessage());
        }
        return ResultEntity.successWithoutData();
    }

    @RequestMapping("/redis/get/value/remote")
    public ResultEntity<String> getValueByKey(@RequestParam("key") String key) {
        try {
            ValueOperations<String, String> operations = redisTemplate.opsForValue();

            // 根据key获取value
            String value = operations.get(key);

            return ResultEntity.successWithData(value);

        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.failed(e.getMessage());
        }
    }

    @RequestMapping("/redis/remove/key/remote")
    public ResultEntity<String> removeKey(@RequestParam("key") String key) {
        try {

            // 删除key
            redisTemplate.delete(key);

            return ResultEntity.successWithoutData();

        } catch (Exception e) {
            e.printStackTrace();

            return ResultEntity.failed(e.getMessage());
        }
    }
}

 

posted on 2019-10-27 16:04  AllBlu  阅读(129)  评论(0编辑  收藏  举报