SpringBoot集成Redis

导入依赖


    org.springframework.boot
    spring-boot-starter-parent
    1.5.3.RELEASE


    
        org.springframework.boot
        spring-boot-starter-data-redis
    
    
    
        org.springframework.boot
        spring-boot-starter-data-redis
    
    
    
        org.springframework.boot
        spring-boot-starter-web
    

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 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 stringList=new ArrayList<>();
        stringList.add("张三");
        stringList.add("李四");
        stringList.add("王五");
        springBootRedis.set("listKey",stringList);
    }

    @RequestMapping("/setSet")
    public void setSet(){
        Set 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);
    }
}

你可能感兴趣的:(SpringBoot集成Redis)