SpringBoot集成Redis

导入依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
    <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>
</dependencies>

application.yml文件

spring:
  redis:
    database: 0
    host: 192.168.30.128
    port: 6973

SpringBootRedis类

@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);
        }
    }
}

SpringBootController类 

@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);
    }
}

启动类StartSpringBoot

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class StartSpringBoot {
    public static void main(String[] args) {
        SpringApplication.run(StartSpringBoot.class,args);
    }
}
posted @ 2020-01-02 09:48  慕容子月  阅读(278)  评论(0编辑  收藏  举报