1、目录展示

  

2、导入依赖

  

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

3、application.yml文件

  

4、SpringBootRedis类 

package com.zn.redis;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class SpringBootRedis {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void set(String key,Object value){
        if (value instanceof String){
            stringRedisTemplate.opsForValue().set(key,(String)value,200L, TimeUnit.SECONDS);
        }else if (value instanceof List){
            List<String> list=(List)value;
            for (String item:list){
                stringRedisTemplate.opsForList().leftPush(key,item);
            }
        }else if (value instanceof Set){
            String[] objects=(String[]) ((Set) value).toArray(new String[((Set) value).size()]);
            stringRedisTemplate.opsForSet().add(key,objects);
        }else if (value instanceof Map){
            stringRedisTemplate.opsForHash().putAll(key,(Map<?,?>)value);
        }
    }
}

5、SpringBootController类 

package com.zn.controller;

import com.zn.redis.SpringBootRedis;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@RestController
public class SpringBootController {
    @Resource
    private SpringBootRedis springBootRedis;

    @RequestMapping("/setString")
    public void setString(){
        springBootRedis.set("setKey","setValue");
    }

    @RequestMapping("/setList")
    public void setList(){
        List<String> stringList=new ArrayList<>();
        stringList.add("张三");
        stringList.add("李四");
        stringList.add("王五");
        springBootRedis.set("listKey",stringList);
    }

    @RequestMapping("/setSet")
    public void setSet(){
        Set<String> set=new HashSet<>();
        set.add("北京");
        set.add("上海");
        set.add("广州");
        springBootRedis.set("setKey",set);
    }

    @RequestMapping("/setMap")
    public void setMap(){
        Map map=new HashMap();
        map.put("name","张三");
        map.put("age","18");
        springBootRedis.set("mapKey",map);
    }
}

6、启动类StartSpringBoot

  

 7、效果展示

  (1)string

    

     

  (2)list

    

  (3)set

    

  (4)map

    

  

12-24 22:16