SpringBoot統合RedisおよびStringRedisTemplateの使用

2123 ワード

Maven依存

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



プロファイル
#redis ip    
spring.redis.hostName=127.0.0.1
#   ,   0
spring.redis.database=0
#     
spring.redis.port=6379
#       
spring.redis.password=
#                2000 
spring.redis.timeout=10000  


StringRedisTemplate使用
stringRedisTemplate.opsForValue();//     
stringRedisTemplate.opsForHash();//  hash
stringRedisTemplate.opsForList();//  list
stringRedisTemplate.opsForSet();//  set
stringRedisTemplate.opsForZSet();//    set

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * stringRedisTemplate    
     */
    public void redis(){
        stringRedisTemplate.opsForValue().set("key", "value",60*5, TimeUnit.SECONDS);// redis            (5  )
        stringRedisTemplate.boundValueOps("key").increment(-1);//val -1  
        stringRedisTemplate.opsForValue().get("key");//  key      val
        stringRedisTemplate.boundValueOps("key").increment(1);//val +1
        stringRedisTemplate.getExpire("key");//  key      
        stringRedisTemplate.getExpire("key",TimeUnit.SECONDS);//  key              
        stringRedisTemplate.delete("key");//  key    
        stringRedisTemplate.hasKey("key");//  key    ,  boolean 
        stringRedisTemplate.opsForSet().add("key", "1","2","3");//   key   set  
        stringRedisTemplate.expire("key",1000 , TimeUnit.MILLISECONDS);//      
        stringRedisTemplate.opsForSet().isMember("key", "1");//  key             
        stringRedisTemplate.opsForSet().members("key");//  key  set  

    }
}