存储对象的三种方式分别为:

1.将对象序列化后保存到Redis
2.将对象用FastJSON转为JSON字符串后存储
3.将对象用Hash数据类型存储

这里RedisTemplate用自定义方式

/**
* 自定义RedisTemplate,修改其序列化方法
*/
@Configuration
public class RedisConfig {

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory){
		// 创建RedisTemplate对象
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		// 设置连接工厂
		template.setConnectionFactory(connectionFactory);
		// 创建JSON序列化工具
		GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
		// 设置Key的序列化
		template.setKeySerializer(RedisSerializer.string());
		template.setHashKeySerializer(RedisSerializer.string());
		// 设置Value的序列化
		template.setValueSerializer(jsonRedisSerializer);
		template.setHashValueSerializer(jsonRedisSerializer);
		// 返回
		return template;
	}
}

序列化工具类SerializeUtil

public class SerializeUtil {
    /*
     * 序列化
     * */
    public static byte[] serizlize(Object object){
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(baos != null){
                    baos.close();
                }
                if (oos != null) {
                    oos.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }
    /*
     * 反序列化
     * */
    public static Object deserialize(byte[] bytes){
        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null; 
        try{
            bais = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(bais);
            return ois.readObject();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            try {
 
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return null;
    }
}

User

public class User implements Serializable{
    private static final long serialVersionUID = -3210884885630038713L;
    private int id;
    private String name;
    public User(){
 
    }
    public User(int id,String name){
        this.id = id;
        this.name = name;
    }
    //setter和getter方法
}

方式1.将对象序列化后保存到Redis

@Component
public class VisitCounterScheduler {

    @Autowired
    private VisitCounterMapper visitCounterMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Scheduled(cron = "0 59 * * * *")
    public void postDailyVisitCount2Redis() {
        redisTemplate.opsForValue().set("dailyVisitCount", SerializeUtil.serizlize(new User(2,"lumia")));
    }
}

方式2.将对象用FastJSON转为JSON字符串后存储

package com.aac.bpmmanager.scheduler;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unchecked")
@Component
public class VisitCounterScheduler {

    @Autowired
    private VisitCounterMapper visitCounterMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Scheduled(cron = "0 59 * * * *")
    public void postDailyVisitCount2Redis() {
        User user = new user(1, "zhangsanfeng");
        String s = JSON.toJSONString(user);
        //存放对象方式二:将对象用FastJSON转为JSON字符串后存储
        redisTemplate.opsForValue().set("user1", JSON.toJSONString(user));
    }
}

方式3.将对象用Hash数据类型存储

利用Hash存储对象,适用于字段的某些值经常变化,而部门值不变化,比如余额宝,余额经常变化可以用Hash存储,余额宝其它字段数据不经常变化。

package com.server;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pojo.Student;

@Service
public class StudentServer {

   @Autowired
   private RedisTemplate redisTemplate;//redisTemplate操作redis
   
   public void setmap(){
   	User stu=new User();
   	//标志map的键、标志value的key、value
   	//向键名为stu.getStuid的map对象存储key-value对
   	HashOperations<String, String, String> map=redisTemplate.opsForHash().put(stu.getId, "name", stu.getName);
   	
   	//设置100 seconds存活时间
   	redisTemplate.expire(stu.getStuid, 100, TimeUnit.SECONDS);
   }
}

参考文章
https://blog.csdn.net/qq_26545503/article/details/106123676
http://www.voidcn.com/article/p-rsqqqrgq-qw.html
https://blog.csdn.net/qq_44909430/article/details/104649464
https://blog.csdn.net/xzd315752647/article/details/86318870

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐