下面列出了怎么用com.alibaba.fastjson.TypeReference的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void init() throws Exception {
// A fake path.
String flowRuleDir = System.getProperty("user.home") + "/sentinel/rules";
String flowRuleFile = "flowRule.json";
String flowRulePath = flowRuleDir + "/" + flowRuleFile;
ReadableDataSource<String, List<FlowRule>> ds = new FileRefreshableDataSource<>(
flowRulePath, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {})
);
// Register to flow rule manager.
FlowRuleManager.register2Property(ds.getProperty());
WritableDataSource<List<FlowRule>> wds = new FileWritableDataSource<>(flowRulePath, this::encodeJson);
// Register to writable data source registry so that rules can be updated to file
// when there are rules pushed from the Sentinel Dashboard.
WritableDataSourceRegistry.registerFlowDataSource(wds);
}
@Override
public CommandResponse<String> handle(CommandRequest request) {
String data = request.getParam("data");
if (StringUtil.isBlank(data)) {
return CommandResponse.ofFailure(new IllegalArgumentException("Bad data"));
}
try {
data = URLDecoder.decode(data, "utf-8");
} catch (Exception e) {
RecordLog.info("Decode gateway rule data error", e);
return CommandResponse.ofFailure(e, "decode gateway rule data error");
}
RecordLog.info(String.format("[API Server] Receiving rule change (type: gateway rule): %s", data));
String result = SUCCESS_MSG;
Set<GatewayFlowRule> flowRules = JSON.parseObject(data, new TypeReference<Set<GatewayFlowRule>>() {
});
GatewayRuleManager.loadRules(flowRules);
if (!writeToDataSource(gatewayFlowWds, flowRules)) {
result = WRITE_DS_FAILURE_MSG;
}
return CommandResponse.ofSuccess(result);
}
@Override
public CommandResponse<String> handle(CommandRequest request) {
String data = request.getParam("data");
if (StringUtil.isBlank(data)) {
return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
}
try {
data = URLDecoder.decode(data, "utf-8");
RecordLog.info("[ModifyServerNamespaceSetHandler] Receiving cluster server namespace set: " + data);
Set<String> set = JSON.parseObject(data, new TypeReference<Set<String>>() {});
ClusterServerConfigManager.loadServerNamespaceSet(set);
return CommandResponse.ofSuccess("success");
} catch (Exception e) {
RecordLog.warn("[ModifyServerNamespaceSetHandler] Decode cluster server namespace set error", e);
return CommandResponse.ofFailure(e, "decode client cluster config error");
}
}
private static void loadRules2() {
final String remoteAddress = "127.0.0.1:2181";
// 引入groupId和dataId的概念,是为了方便和Nacos进行切换
final String groupId = "Sentinel-Demo";
final String flowDataId = "SYSTEM-CODE-DEMO-FLOW";
// final String degradeDataId = "SYSTEM-CODE-DEMO-DEGRADE";
// final String systemDataId = "SYSTEM-CODE-DEMO-SYSTEM";
// 规则会持久化到zk的/groupId/flowDataId节点
// groupId和和flowDataId可以用/开头也可以不用
// 建议不用以/开头,目的是为了如果从Zookeeper切换到Nacos的话,只需要改数据源类名就可以
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(remoteAddress, groupId, flowDataId,
source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
// ReadableDataSource<String, List<DegradeRule>> degradeRuleDataSource = new ZookeeperDataSource<>(remoteAddress, groupId, degradeDataId,
// source -> JSON.parseObject(source, new TypeReference<List<DegradeRule>>() {}));
// DegradeRuleManager.register2Property(degradeRuleDataSource.getProperty());
//
// ReadableDataSource<String, List<SystemRule>> systemRuleDataSource = new ZookeeperDataSource<>(remoteAddress, groupId, systemDataId,
// source -> JSON.parseObject(source, new TypeReference<List<SystemRule>>() {}));
// SystemRuleManager.register2Property(systemRuleDataSource.getProperty());
}
private static void loadRules() {
// Set up basic information, only for demo purpose. You may adjust them based on your actual environment.
// For more information, please refer https://github.com/ctripcorp/apollo
String appId = "sentinel-demo";
String apolloMetaServerAddress = "http://localhost:8080";
System.setProperty("app.id", appId);
System.setProperty("apollo.meta", apolloMetaServerAddress);
String namespaceName = "application";
String flowRuleKey = "flowRules";
// It's better to provide a meaningful default value.
String defaultFlowRules = "[]";
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ApolloDataSource<>(namespaceName,
flowRuleKey, defaultFlowRules, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
}));
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
/**
* 恢复快照
*
* @return
* @throws IOException
*/
public ConcurrentMap<ConsumePartition, Position> recover() throws IOException {
ConcurrentMap<ConsumePartition, Position> consumePositionCache = new ConcurrentHashMap<>();
Map<Joint, List<ConsumeBill>> consumeBills;
try {
consumeBills = loadFromFile(indexFile, new TypeReference<Map<Joint, List<ConsumeBill>>>() {
});
} catch (Exception e) {
consumeBills = loadFromFile(indexFileBack, new TypeReference<Map<Joint, List<ConsumeBill>>>() {
});
}
if (consumeBills != null) {
consumeBills.entrySet().stream().forEach(entry -> {
Joint key = entry.getKey();
entry.getValue().stream().forEach(val ->
consumePositionCache.putIfAbsent(new ConsumePartition(key.getTopic(), key.getApp(), val.getPartition()),
new Position(val.getAckStartIndex(), val.getAckCurIndex(), val.getPullStartIndex(), val.getPullCurIndex()))
);
});
}
return consumePositionCache;
}
@Override
public Object decode(final JoyQueueHeader header, final ByteBuf buffer) throws Exception {
String consumePositions;
if (header.getVersion() == JoyQueueHeader.VERSION_V1) {
consumePositions = Serializer.readString(buffer, Serializer.SHORT_SIZE);
} else {
consumePositions = Serializer.readString(buffer, Serializer.INT_SIZE);
}
if (consumePositions != null) {
Map<ConsumePartition, Position> connections = JSON.parseObject(consumePositions, new TypeReference<Map<ConsumePartition, Position>>() {
});
return new ReplicateConsumePosRequest(connections);
}
return new ReplicateConsumePosRequest();
}
@Test
public void testEurekaDataSource() throws Exception {
String url = "http://localhost:" + port + "/eureka";
EurekaDataSource<List<FlowRule>> eurekaDataSource = new EurekaDataSource(appname, instanceId, Arrays.asList(url)
, SENTINEL_KEY, new Converter<String, List<FlowRule>>() {
@Override
public List<FlowRule> convert(String source) {
return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
});
}
});
FlowRuleManager.register2Property(eurekaDataSource.getProperty());
await().timeout(15, TimeUnit.SECONDS)
.until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return FlowRuleManager.getRules().size() > 0;
}
});
Assert.assertTrue(FlowRuleManager.getRules().size() > 0);
}
@GetMapping("/recommend")
public ResponseMessage getRecommendUser(
@RequestParam String param) {
List<CompanyAndJob> companyAndJobList = JSONObject.parseObject(param, new TypeReference<List<CompanyAndJob>>() {
});
return ResponseMessage.successMessage(userInfoService.getRecommendUser(companyAndJobList));
}
public void initCameraParams(JSONObject rt) {
CameraCurParamsJson curParamsJson = (CameraCurParamsJson) JSON.parseObject(rt.toString(), new TypeReference<CameraCurParamsJson>() {
}, new Feature[0]);
if (curParamsJson != null && curParamsJson != null) {
X8sMainActivity.this.mX8MainBottomParameterController.initCameraParam(curParamsJson);
}
}
/**
* 此方法接收 前台信息
*
* @param message
* @param session
*/
@OnMessage
public void onMessage(String message, Session session) {
if (StringUtils.isEmpty(message)) {
return;
}
MessageCommonDTO messageCommonDTO = JSON.parseObject(message, new TypeReference<MessageCommonDTO>() {});
if (MessageTypeEnum.HEART_BEAT.getValue().equals(messageCommonDTO.getMessageType())) {
this.heartBeatHandle(messageCommonDTO.getJsonStr());
}
}
/**
* 更新用户过期时间
*
* @param json
*/
private void heartBeatHandle(String json) {
Long currentDate = System.currentTimeMillis();
Long expireTime = currentDate + 5 * 1000;
WebSocketHeartBeatDTO heartBeatDTO = JSON.parseObject(json, new TypeReference<WebSocketHeartBeatDTO>() {});
Long employeeId = heartBeatDTO.getEmployeeId();
onLineUser.put(employeeId, expireTime);
}
public <T> Map<String, T> entries(String key, TypeReference<T> type) {
HashOperations<String, String, String> ops = redisTemplate.opsForHash();
Map<String, T> rs = new HashMap<>();
ops.entries(formatKey(key)).forEach((k, v) -> {
rs.put(k, parseObject(v, type));
});
return rs;
}
@GetMapping("/recommend")
public ResponseMessage getRecommendUser(
@RequestParam String param) {
List<CompanyAndJob> companyAndJobList = JSONObject.parseObject(param, new TypeReference<List<CompanyAndJob>>() {
});
return ResponseMessage.successMessage(userInfoService.getRecommendUser(companyAndJobList));
}
private void initServerTransportConfigProperty() {
ReadableDataSource<String, ServerTransportConfig> serverTransportDs = new NacosDataSource<>(remoteAddress, groupId,
clusterMapDataId, source -> {
List<ClusterGroupEntity> groupList = JSON.parseObject(source, new TypeReference<List<ClusterGroupEntity>>() {});
return Optional.ofNullable(groupList)
.flatMap(this::extractServerTransportConfig)
.orElse(null);
});
ClusterServerConfigManager.registerServerTransportProperty(serverTransportDs.getProperty());
}
public List<Address> getCityList() {
if (StringUtils.isBlank(this.city)) {
return new ArrayList<>();
}
this.cityList = JSONObject.parseObject(city, new TypeReference<List<Address>>(){});
return cityList;
}
private void initStateProperty() {
// Cluster map format:
// [{"clientSet":["[email protected]","[email protected]"],"ip":"112.12.88.68","machineId":"[email protected]","port":11111}]
// machineId: <[email protected]>, commandPort for port exposed to Sentinel dashboard (transport module)
ReadableDataSource<String, Integer> clusterModeDs = new NacosDataSource<>(remoteAddress, groupId,
clusterMapDataId, source -> {
List<ClusterGroupEntity> groupList = JSON.parseObject(source, new TypeReference<List<ClusterGroupEntity>>() {});
return Optional.ofNullable(groupList)
.map(this::extractMode)
.orElse(ClusterStateManager.CLUSTER_NOT_STARTED);
});
ClusterStateManager.registerProperty(clusterModeDs.getProperty());
}
/**
* 将JSON字符串转化为MAP对象
* @param json JSON字符串
*/
public static final Map<String, Object> convertJsonToMap(String json) {
Map<String, Object> map = JSON.parseObject(json, new TypeReference<Map<String, Object>>() {
});
return map;
}
private static void loadMyNamespaceRules() {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
properties.put(PropertyKeyConst.NAMESPACE, NACOS_NAMESPACE_ID);
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,
source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
}));
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
@Override
@RequestMapping("/menuauth")
@RequiresRoles("admin_sys")
@RequiresPermissions(value={"sys:role:auth"})
public String menuauth(@RequestBody Map<String, Object> sys) {
List<SysMenu> sysMenus = JSON.parseObject(String.valueOf(JSON.toJSON(sys.get("sysMenus"))), new TypeReference<List<SysMenu>>() {});
String roleId= (String) sys.get("roleId");
String moduleId= (String) sys.get("moduleId");
int result=sysRoleService.menuAuth(sysMenus,roleId,moduleId);
if(result>0) {
return JSON.toJSONString ("true");
}else{
return JSON.toJSONString ("false");
}
}
@Test
public void testZooKeeperDataSource() throws Exception {
TestingServer server = new TestingServer(21812);
server.start();
final String remoteAddress = server.getConnectString();
final String path = "/sentinel-zk-ds-demo/flow-HK";
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<List<FlowRule>>(remoteAddress, path,
new Converter<String, List<FlowRule>>() {
@Override
public List<FlowRule> convert(String source) {
return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
});
}
});
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
CuratorFramework zkClient = CuratorFrameworkFactory.newClient(remoteAddress,
new ExponentialBackoffRetry(3, 1000));
zkClient.start();
Stat stat = zkClient.checkExists().forPath(path);
if (stat == null) {
zkClient.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path, null);
}
final String resourceName = "HK";
publishThenTestFor(zkClient, path, resourceName, 10);
publishThenTestFor(zkClient, path, resourceName, 15);
zkClient.close();
server.stop();
}
private static void loadMyNamespaceRules() {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
properties.put(PropertyKeyConst.NAMESPACE, NACOS_NAMESPACE_ID);
ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,
source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
}));
FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
public static <T> T toObject(String json, TypeReference<T> typeReference) {
try {
return JSON.parseObject(json, typeReference);
} catch (Exception e) {
LOGGER.error("toObject exception, err:{}", e.getMessage(), e);
}
return null;
}
/**
* 初始化集群限流的Supplier
* 这样如果后期集群限流的规则发生变更的话,系统可以自动感知到
*/
private void initClusterFlowSupplier() {
// 为集群流控注册一个Supplier,该Supplier会根据namespace动态创建数据源
ClusterFlowRuleManager.setPropertySupplier(namespace -> {
// 使用 Nacos 数据源作为配置中心,需要在 REMOTE_ADDRESS 上启动一个 Nacos 的服务
ReadableDataSource<String, List<FlowRule>> ds = new NacosDataSource<>(REMOTE_ADDRESS, GROUP_ID,
namespace + FLOW_POSTFIX,
source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
return ds.getProperty();
});
}
/**
* 初始化集群热点参数限流的Supplier
* 这样如果后期集群热点参数限流的规则发生变更的话,系统可以自动感知到
*/
public void initClusterParamFlowSupplier() {
// 为集群热点参数流控注册一个Supplier,该Supplier会根据namespace动态创建数据源
ClusterParamFlowRuleManager.setPropertySupplier(namespace -> {
// 使用 Nacos 数据源作为配置中心,需要在 REMOTE_ADDRESS 上启动一个 Nacos 的服务
ReadableDataSource<String, List<ParamFlowRule>> ds = new NacosDataSource<>(REMOTE_ADDRESS, GROUP_ID,
namespace + PARAM_FLOW_POSTFIX,
source -> JSON.parseObject(source, new TypeReference<List<ParamFlowRule>>() {}));
return ds.getProperty();
});
}
@Override
public void addColumn(TableField tableField) {
//添加字典
addColumnToDict(tableField);
addFiledCommentValue(tableField);
String json = JSONObject.toJSONString(tableField);
Map<String,Object> map = JSON.parseObject(json,new TypeReference<HashMap<String,Object>>() {});
tableDao.addColumn(map);
changeTableComment(tableField.getTableName(),tableField.getTableComment(),tableField.getTableType());
}
/**
* 解析json串,返回List<ColumnMeta>
*
* @param json
* @return
*/
private static List<ColumnMeta> parseColumnsJson(String json) {
LinkedHashMap<String, String> jsonMap = JSON.parseObject(json, new TypeReference<LinkedHashMap<String, String>>() {
});
List<ColumnMeta> columns = new ArrayList<>();
for (Map.Entry<String, String> hdfs_meta : jsonMap.entrySet()) {
if ("fields".equals(hdfs_meta.getKey())) {
//如果key是fields,则继续遍历获取所有字段类型
ArrayList<String> list = JSON.parseObject(hdfs_meta.getValue(), new TypeReference<ArrayList<String>>() {
});
for (String types : list) {
//第三层遍历,获取所有类型
LinkedHashMap<String, String> types_info = JSON.parseObject(types, new TypeReference<LinkedHashMap<String, String>>() {
});
for (Map.Entry<String, String> field_type : types_info.entrySet()) {
ColumnMeta cm = new ColumnMeta();
cm.setName(field_type.getKey());
cm.setType(field_type.getValue());
//cm.set
columns.add(cm);
}
}
}
}
return columns;
}
/**
* 用户登录时,存入jwt信息,更新用户无法,更新jwt
*
* @param token
* @return
*/
public RedisUser jwtUser(String token) {
String tok = jwtTokenUtil.getUsernameFromToken(token);
RedisUser redisUser = JSON.parseObject(tok, new TypeReference<RedisUser>() {
});
return redisUser;
}
@Override
protected DescribeBinlogFileResult processResult(HttpResponse response) throws Exception {
String result = EntityUtils.toString(response.getEntity());
DescribeBinlogFileResult describeBinlogFileResult = JSONObject.parseObject(result,
new TypeReference<DescribeBinlogFileResult>() {
});
return describeBinlogFileResult;
}
public static <K, V> Map<K, V> parseToMap(String json,
Class<K> keyType,
Class<V> valueType) {
return JSON.parseObject(json,
new TypeReference<Map<K, V>>(keyType, valueType) {
});
}