自定义Redis Template(保姆级)

自定义Redis Template(保姆级),第1张

自定义Redis Template(保姆级) 一、自己定义RedisTemplate     序列化
package com.kuang.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.codec.cbor.Jackson2CborDecoder;

import java.net.UnknownHostException;

@Configuration
public class RedisConfig {
// 编写自己的redisTemplate
@Bean
@SuppressWarnings("all")
public RedisTemplate redisTemplate(RedisConnectionFactory factory)
throws UnknownHostException {
// 为了方便,一般直接使用String Object
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);

// Jason序列化配置
Jackson2JsonRedisSerializer objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
objectJackson2JsonRedisSerializer.setObjectMapper(om);
// String的序列化
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化
template.setKeySerializer(stringRedisSerializer);
// Hash 的key采用
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(objectJackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(objectJackson2JsonRedisSerializer);
template.afterPropertiesSet();
// 配置具体的序列化方式
return template;
}

}
 
 二、自己定义RedisUtil(只给出了部分) 
 

自己设置一些方法,可以供redisUtil使用

package com.kuang.utils;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate redisTemplate;

    
    public boolean expire(String key,long time){
        try{
            if( time > 0){
                redisTemplate.expire(key,time, TimeUnit.SECONDS);
            }
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public long getExpire(String key){
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }
    // 判断KEY是否存在
    public boolean hasKey(String key){
        try{
            return redisTemplate.hasKey(key);
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
    // 删除缓存
    public void del(String... key){
        if(key!=null && key.length > 0){
            if(key.length == 1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete((Collection) CollectionUtils.arrayToList(key));
            }
        }
    }
    public boolean set(String key,Object value){
        try{
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }
    // 普通缓存放入并设置时间
    public boolean set(String key,Object value,long time){
        try{
            if(time > 0){
                redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            }else{
                set(key,value);
            }
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }

    // 递增
    public  long incr(String key,long delta){
        if(delta < 0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key,delta);
    }

    // 递减
    public  long decr(String key,long delta){
        if(delta < 0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key,-delta);
    }

    public Object hget(String key,String item){
        return redisTemplate.opsForHash().get(key,item);
    }

    public Map hmget(String key){
        return redisTemplate.opsForHash().entries(key);
    }

}

测试:
package com.kuang;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kuang.pojo.User;
import com.kuang.utils.RedisUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;

import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class Redis02SpringbootApplicationTests {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisUtil redisUtil;

    @Test
    public void test1(){
        redisUtil.set("vivi",9);
        //redisUtil.incr("vivi",10);
        System.out.println(redisUtil.incr("vivi",9));
    }


    @Test
    void contextLoads() {
// redisTemplate  *** 作不同的数据类型,api和我们的指令是一样的
// opsForValue
// opsForList
// opsForSet
// opsForHash
// opsForZSet
// opsForGeo
// 除了进本的 *** 作,我们常用的方法都可以直接redisTemplate *** 作,比如事务、和基本的CRUD
// 获取Redis的连接对象
        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
        connection.flushDb();
        connection.flushAll();
        redisTemplate.opsForValue().set("key", "java");
        System.out.println(redisTemplate.opsForValue().get("key"));
    }
    @Test
    public void test() throws JsonProcessingException {
        // 真实的开发一般都使用json来传递对象
      User user = new User("狂神说",3);
      String jsonUser  = new ObjectMapper().writevalueAsString(user);
      redisTemplate.opsForValue().set("user",jsonUser);
      System.out.println(redisTemplate.opsForValue().get("user"));
    }

}
在项目中自己建立redisTemplate方法, 注意: 测试的时候不要忘了 @Qualifier ( "redisTemplate" ),表示使用自己定义的方法,而不是系统自带的。 结果如下:

 

三、关于为什么要序列化? 打开Redis的“redis-clc.exe,输入“keys*”,如果不想输出一堆乱码就最好序列化redisTemplate(开发中都要pojo序列化)

 

 序列化以后:

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5562843.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)