001/** 002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package io.jboot.components.serializer; 017 018import io.jboot.Jboot; 019import io.jboot.core.spi.JbootSpiLoader; 020import io.jboot.exception.JbootIllegalConfigException; 021import io.jboot.utils.StrUtil; 022 023import java.util.Map; 024import java.util.concurrent.ConcurrentHashMap; 025 026 027public class JbootSerializerManager { 028 029 030 private static JbootSerializerManager me = new JbootSerializerManager(); 031 032 private static Map<String, JbootSerializer> serializerCaches = new ConcurrentHashMap<>(); 033 034 public static JbootSerializerManager me() { 035 return me; 036 } 037 038 039 public JbootSerializer getSerializer() { 040 JbootSerializerConfig config = Jboot.config(JbootSerializerConfig.class); 041 if (StrUtil.isBlank(config.getType())) { 042 throw new JbootIllegalConfigException("can not get serializer config, please set jboot.serializer value to jboot.proerties"); 043 } 044 return getSerializer(config.getType()); 045 } 046 047 048 public JbootSerializer getSerializer(String serializerName) { 049 JbootSerializer serializer = serializerCaches.get(serializerName); 050 if (serializer == null) { 051 synchronized (this) { 052 serializer = serializerCaches.get(serializerName); 053 if (serializer == null) { 054 serializer = buildSerializer(serializerName); 055 serializerCaches.put(serializerName, serializer); 056 } 057 } 058 } 059 060 return serializer; 061 } 062 063 public JbootSerializer buildSerializer(String serializerName) { 064 if (serializerName == null) { 065 throw new NullPointerException("SerializerName must not be null"); 066 } 067 068 069 switch (serializerName.toLowerCase()) { 070 case JbootSerializerConfig.KRYO: 071 return new KryoSerializer(); 072 case JbootSerializerConfig.FST: 073 return new FstSerializer(); 074 case JbootSerializerConfig.FASTJSON: 075 return new FastJsonSerializer(); 076 default: 077 return JbootSpiLoader.load(JbootSerializer.class, serializerName); 078 } 079 } 080 081 082}