Srpingboot项目启动后初始化信息到redis

1.我这边写了一个序列化的接口

public class FstSerializer {

	private static final Logger logger = LoggerFactory.getLogger(FstSerializer.class);
	private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration().setForceSerializable(false);

	private static FstSerializer instance = null;

	/**
	 * 
	 * @return
	 */
	public static FstSerializer getInstance() {
		if (instance == null) {
			synchronized (FstSerializer.class) {
				if (instance == null) {
					instance = new FstSerializer();
				}
			}
		}
		return instance;
	}

	private FstSerializer() {
	}

	/**
	 * 序列化
	 * @param object
	 * @return
	 */
	public byte[] serialize(Object object) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		FSTObjectOutput out = this.conf.getObjectOutput(stream);
		try {
			out.writeObject(object);
			out.flush();
			stream.close();
		} catch (IOException e) {
			logger.error("serialize error", e);
		}
		return stream.toByteArray();
	}

	/**
	 * 反序列化
	 * @param arr
	 * @param cls
	 * @return
	 */
	public  T deserialize(byte[] arr, Class cls) {
		T result = null;
		try {
			ByteArrayInputStream stream = new ByteArrayInputStream(arr);
			FSTObjectInput in = this.conf.getObjectInput(stream);
			result = (T) in.readObject();
			stream.close();
		} catch (Exception e) {
			logger.error("deserialize error", e);
		}
		return result;
	}

2.把数据库的数据初始化到redis进行保存,后面可以直接到redis拿来用,经常用到的数据

public class InitSmsParamUtil {
    private final static Logger logger = LoggerFactory.getLogger(InitSmsParamUtil.class);

    @Autowired
    private SmsParamService smsParamService;

    public void initSmsParamRedis(){
        List> smsOperatorList = smsParamService.listSmsOperator();
        //序列化
        byte[] smsOperatorBytes = FstSerializer.getInstance().serialize(smsOperatorList);
        RedisService.getRedisService().setByte(RedisKeyConstants.SMS_OPERATOR, smsOperatorBytes);
        RedisService.getRedisService().persist(RedisKeyConstants.SMS_OPERATOR);
        logger.info("==短信运营商参数加载成功==");
    }

 

你可能感兴趣的:(JAVA)