springboot--redis(实现redis的数据操作)和 StringRedisTemplate的常用方法

版权声明:帅气Dee海绵宝宝 https://blog.csdn.net/xyjcfucdi128/article/details/84939994

引入依赖

<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");

猜你喜欢

转载自blog.csdn.net/xyjcfucdi128/article/details/84939994