SpringBoot和Redis整合

1、pom.xml

        <!--springboot中的redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2、RedisControl.java

package com.csp.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class RedisController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/find")
    public String find(@RequestBody JSONObject req){
        String key = req.getString("key");
        try {
            String value =  redisTemplate.opsForValue().get(key);
            return value;
        }catch (Exception e){
            return "failed";
        }
    }

    @PostMapping("/add")
    public String add(@RequestBody JSONObject req){
        String key = req.getString("key");
        String value= req.getString("value");
        try {
            redisTemplate.opsForValue().set(key, value);
            return "success";
        }catch (Exception e){
            return "failed";
        }
    }
}

 

posted @ 2022-01-05 16:37  spring8889  阅读(65)  评论(0)    收藏  举报