springBoot 简易配置 Redis

1、pom.xml 依赖

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

2、yml 基础配置

#redis 配置
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    password: 
    # 连接超时时间
    timeout: 3000

3、java文件中使用

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class RedisController {
          
   

//    redis
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    final static Map<String, String> map = new HashMap<>();

    static {
          
   
        map.put("hashMap1", "hashMap1");
        map.put("hashMap2", "hashMap2");
    }

    @GetMapping("/set")
    public String setRedisValue() {
          
   

        try {
          
   
            stringRedisTemplate.opsForValue().set("setValue", "这是测试数据");
            return "成功";
        } catch (Exception e) {
          
   
            return "失败";
        }
    }

    @GetMapping("/setHash")
    public String hashRedisValue() {
          
   
        try {
          
   
            stringRedisTemplate.opsForHash().put("hashValue", "hash1", "hash1");
            stringRedisTemplate.opsForHash().putAll("hashMap", map);
            return "成功";
        } catch (Exception e) {
          
   
            return "失败";
        }
    }

    @GetMapping("/get")
    public String getRedisValue() {
          
   
        try {
          
   
            return stringRedisTemplate.opsForValue().get("setValue");
        } catch (Exception e) {
          
   
            return "失败";
        }
    }

    @GetMapping("/getHash")
    public Object getRedisHash() {
          
   
        try {
          
   
            return stringRedisTemplate.opsForHash().get("hashMap", "hashMap2");
        } catch (Exception e) {
          
   
            System.out.println(e);
            return "失败";
        }
    }
}

4、Redis Desktop Manager 管理器中查看。

经验分享 程序员 微信小程序 职场和发展