1. 程式人生 > >springboot--redis(實現redis的資料操作)和 StringRedisTemplate的常用方法

springboot--redis(實現redis的資料操作)和 StringRedisTemplate的常用方法

引入依賴

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

application.properties配置檔案

#redis埠,預設6379
# redis配置檔案
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.pool.max-idle=20

JsonUtils工具類

package com.big.data.lab.text;

import java.util.List;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
 
 
/**
 * wangmx  
 * redis 自定義響應結果
 */
public class JsonUtils {
 
    // 定義jackson物件
    private static final ObjectMapper MAPPER = new ObjectMapper();
 
    /**
     * 將物件轉換成json字串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 將json結果集轉化為物件
     * 
     * @param jsonData json資料
     * @param clazz 物件中的object型別
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 將json資料轉換成pojo物件list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
    
}

Controller

         StringRedisTemplate繼承了RedisTemplate。繼承RedisTempalte,與RedisTemplate不同的是設定了序列化策略,使用StringRedisSerializer類來序列化key-value,以及List、Hash、Set。在這裡,我們直接用就行了。
         

package com.big.data.lab.text;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.entity.User;

@Controller
@RequestMapping(value="/redis/test")
public class RedisTest1 {

	@Autowired
	private StringRedisTemplate redisClient;
	
	@RequestMapping("setAndsave")
	@ResponseBody
	public String test() throws Exception{
		String test = "aaaa";
	    redisClient.opsForValue().set("test", test);
	    String str = redisClient.opsForValue().get("test");
	    return str;
	 
	}
	
	@RequestMapping("removeSave")
	@ResponseBody
	public String removeSave() throws Exception{
	    redisClient.delete("test");
	    return "seccess";
	 
	}
	
	@RequestMapping("getjson")
    @ResponseBody
    public String  getJson(){
        User user1 = new User();
        user1.setName("wang");
        user1.setPassword("admin");
        redisClient.opsForValue().set("user", JsonUtils.objectToJson(user1));
        String str = redisClient.opsForValue().get("user");
        String u1  = JsonUtils.objectToJson(user1);
        return str;
	}
	
}

StringRedisTemplate常用操作

1.向redis裡存入資料和設定快取時間  

stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);

2.val做-1操作  

stringRedisTemplate.boundValueOps("test").increment(-1);

3.根據key獲取快取中的val  

stringRedisTemplate.opsForValue().get("test");

4.val +1  

stringRedisTemplate.boundValueOps("test").increment(1);

5.根據key獲取過期時間  

stringRedisTemplate.getExpire("test");

6.根據key獲取過期時間並換算成指定單位 

stringRedisTemplate.getExpire("test",TimeUnit.SECONDS); 

7.根據key刪除快取  

stringRedisTemplate.delete("test");

8.檢查key是否存在,返回boolean值  

stringRedisTemplate.hasKey("546545");

9.向指定key中存放set集合  

stringRedisTemplate.opsForSet().add("red_123", "1","2","3");

10.設定過期時間  

stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);

11.根據key檢視集合中是否存在指定資料  

stringRedisTemplate.opsForSet().isMember("red_123", "1");

12.根據key獲取set集合

stringRedisTemplate.opsForSet().members("red_123");