Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
W
wecloud_im_server
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
hewei
wecloud_im_server
Commits
60b245ba
Commit
60b245ba
authored
Dec 30, 2021
by
lixiaozhong
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
1、json转换性能提升
2、代码结构优化 3、策略模块优化 4、消息体优化
parent
665de18a
Expand all
Hide whitespace changes
Inline
Side-by-side
Showing
26 changed files
with
424 additions
and
354 deletions
+424
-354
bootstrap/src/test/java/io/geekidea/springbootplus/test/JsonTest.java
+6
-9
bootstrap/src/test/java/io/geekidea/springbootplus/test/SignTest.java
+4
-7
core/src/main/java/com/wecloud/im/executor/BusinessThreadPool.java
+2
-2
core/src/main/java/com/wecloud/im/netty/core/WsReadHandler.java
+4
-22
core/src/main/java/com/wecloud/im/netty/handler/NettyApiRequest.java
+6
-6
core/src/main/java/com/wecloud/im/param/add/ImMsgRecall.java
+2
-2
core/src/main/java/com/wecloud/im/service/ImConversationService.java
+1
-1
core/src/main/java/com/wecloud/im/service/ImMessageService.java
+2
-1
core/src/main/java/com/wecloud/im/service/impl/ImConversationMembersServiceImpl.java
+3
-15
core/src/main/java/com/wecloud/im/service/impl/ImConversationServiceImpl.java
+14
-44
core/src/main/java/com/wecloud/im/service/impl/ImMessageServiceImpl.java
+12
-28
core/src/main/java/com/wecloud/im/ws/model/request/PushVO.java
+1
-1
core/src/main/java/com/wecloud/im/ws/model/request/ReceiveDataVO.java
+38
-0
core/src/main/java/com/wecloud/im/ws/model/request/ReceiveVO.java
+4
-3
core/src/main/java/com/wecloud/im/ws/receive/WsDataReader.java
+0
-59
core/src/main/java/com/wecloud/im/ws/sender/AsyncPush.java
+28
-28
core/src/main/java/com/wecloud/im/ws/service/WriteDataService.java
+6
-6
core/src/main/java/com/wecloud/im/ws/service/impl/WriteDataServiceImpl.java
+12
-43
core/src/main/java/com/wecloud/im/ws/strategy/AbstractImCmdStrategy.java
+69
-3
core/src/main/java/com/wecloud/im/ws/strategy/ImCmdStrategyFactory.java
+23
-10
core/src/main/java/com/wecloud/im/ws/strategy/ImCmdStrategyProcessor.java
+0
-53
core/src/main/java/com/wecloud/im/ws/strategy/concrete/NormalChatStrategy.java
+0
-0
core/src/main/java/com/wecloud/im/ws/strategy/concrete/SingleRtcStrategy.java
+2
-6
core/src/main/java/com/wecloud/rtc/service/impl/MangerRtcCacheServiceImpl.java
+3
-4
core/src/main/java/com/wecloud/rtc/service/impl/WsRtcWriteImpl.java
+0
-1
core/src/main/java/com/wecloud/utils/JsonUtils.java
+182
-0
No files found.
bootstrap/src/test/java/io/geekidea/springbootplus/test/JsonTest.java
View file @
60b245ba
package
io
.
geekidea
.
springbootplus
.
test
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.ws.model.request.ReceiveModel
;
import
com.wecloud.im.ws.model.request.ReceiveVO
;
import
com.wecloud.utils.JsonUtils
;
public
class
JsonTest
{
public
static
void
main
(
String
[]
args
)
throws
JsonProcessingException
{
public
static
void
main
(
String
[]
args
)
{
// jsonTest();
}
private
static
void
jsonTest
()
throws
JsonProcessingException
{
private
static
void
jsonTest
()
{
String
data
=
"{\n"
+
"\"reqId\":\"123123\",\n"
+
"\"cmd\":1,\n"
+
...
...
@@ -24,12 +23,10 @@ public class JsonTest {
"}\n"
;
// json转换成对象
JsonMapper
jsonMapper
=
new
JsonMapper
();
ReceiveModel
receiveModel
=
jsonMapper
.
readValue
(
data
,
ReceiveModel
.
class
);
ReceiveVO
receiveVO
=
JsonUtils
.
decodeJson
(
data
,
ReceiveVO
.
class
);
// data对象转换成json
ObjectMapper
objectMapper
=
new
ObjectMapper
();
String
s
=
objectMapper
.
writeValueAsString
(
receiveModel
.
getData
());
JsonUtils
.
encodeJson
(
receiveVO
.
getData
());
}
...
...
bootstrap/src/test/java/io/geekidea/springbootplus/test/SignTest.java
View file @
60b245ba
package
io
.
geekidea
.
springbootplus
.
test
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.ws.model.request.ReceiveModel
;
import
com.wecloud.im.ws.model.request.ReceiveVO
;
import
com.wecloud.utils.JsonUtils
;
import
org.springframework.util.DigestUtils
;
/**
...
...
@@ -52,12 +51,10 @@ public class SignTest {
"}\n"
;
// json转换成对象
JsonMapper
jsonMapper
=
new
JsonMapper
();
ReceiveModel
receiveModel
=
jsonMapper
.
readValue
(
data
,
ReceiveModel
.
class
);
ReceiveVO
receiveVO
=
JsonUtils
.
decodeJson
(
data
,
ReceiveVO
.
class
);
// data对象转换成json
ObjectMapper
objectMapper
=
new
ObjectMapper
();
String
s
=
objectMapper
.
writeValueAsString
(
receiveModel
.
getData
());
JsonUtils
.
encodeJson
(
receiveVO
.
getData
());
}
...
...
core/src/main/java/com/wecloud/im/executor/BusinessThreadPool.java
View file @
60b245ba
...
...
@@ -14,13 +14,13 @@ import java.util.concurrent.TimeUnit;
*/
public
class
BusinessThreadPool
{
private
final
static
ThreadFactory
BUSINESS_THREAD_FACTORY
=
new
ThreadFactoryBuilder
()
private
static
final
ThreadFactory
BUSINESS_THREAD_FACTORY
=
new
ThreadFactoryBuilder
()
.
setNamePrefix
(
"-business-"
).
build
();
/**
* 业务处理线程池
*/
public
final
static
ExecutorService
BUSINESS_TASK_THREAD_POOL_EXECUTOR
=
public
static
final
ExecutorService
BUSINESS_TASK_THREAD_POOL_EXECUTOR
=
new
ThreadPoolExecutor
(
WsConstants
.
CPU_PROCESSORS
,
WsConstants
.
CPU_PROCESSORS
*
2
,
60L
,
TimeUnit
.
MILLISECONDS
,
new
LinkedBlockingQueue
<
Runnable
>(
1024
*
2
),
BUSINESS_THREAD_FACTORY
,
new
ThreadPoolExecutor
.
CallerRunsPolicy
());
...
...
core/src/main/java/com/wecloud/im/netty/core/WsReadHandler.java
View file @
60b245ba
package
com
.
wecloud
.
im
.
netty
.
core
;
import
cn.hutool.core.thread.ThreadFactoryBuilder
;
import
com.wecloud.im.executor.BusinessThreadPool
;
import
com.wecloud.im.ws.model.WsConstants
;
import
com.wecloud.im.ws.receive.WsDataReader
;
import
com.wecloud.im.ws.service.MangerChannelService
;
import
com.wecloud.im.ws.strategy.AbstractImCmdStrategy
;
import
com.wecloud.rtc.service.RtcService
;
import
io.netty.channel.ChannelHandler
;
import
io.netty.channel.ChannelHandlerContext
;
...
...
@@ -16,11 +14,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.stereotype.Component
;
import
javax.annotation.Resource
;
import
java.util.concurrent.ExecutorService
;
import
java.util.concurrent.LinkedBlockingQueue
;
import
java.util.concurrent.ThreadFactory
;
import
java.util.concurrent.ThreadPoolExecutor
;
import
java.util.concurrent.TimeUnit
;
/**
* @Description app端 长连接事件处理
...
...
@@ -34,19 +27,7 @@ public class WsReadHandler extends SimpleChannelInboundHandler<TextWebSocketFram
private
static
final
String
PING
=
"ping"
;
private
static
final
String
PONG
=
"pong"
;
private
final
static
ThreadFactory
NAMED_THREAD_FACTORY
=
new
ThreadFactoryBuilder
()
.
setNamePrefix
(
"WS-business-"
).
build
();
/**
* 耗时核心业务处理线程池
* 属于io密集型业务
* io密集型任务配置尽可能多的线程数量
*/
private
final
static
ExecutorService
TASK_THREAD_POOL_EXECUTOR
=
new
ThreadPoolExecutor
(
WsConstants
.
CPU_PROCESSORS
*
5
,
WsConstants
.
CPU_PROCESSORS
*
10
,
10L
,
TimeUnit
.
MILLISECONDS
,
new
LinkedBlockingQueue
<
Runnable
>(
10
),
NAMED_THREAD_FACTORY
,
new
ThreadPoolExecutor
.
CallerRunsPolicy
());
@Resource
private
WsDataReader
wsDataReader
;
@Autowired
private
RtcService
rtcService
;
@Resource
...
...
@@ -91,7 +72,8 @@ public class WsReadHandler extends SimpleChannelInboundHandler<TextWebSocketFram
return
;
}
wsDataReader
.
convertModel
(
data
,
ctx
,
appKey
,
clientId
);
AbstractImCmdStrategy
.
process
(
appKey
,
clientId
,
ctx
,
data
);
}
catch
(
Exception
e
)
{
log
.
error
(
"系统繁忙data:"
+
data
+
",appKey:"
+
appKey
+
",clientId:"
+
clientId
+
",channelId:"
+
ctx
.
channel
().
id
().
asLongText
(),
e
);
...
...
core/src/main/java/com/wecloud/im/netty/handler/NettyApiRequest.java
View file @
60b245ba
...
...
@@ -3,11 +3,11 @@ package com.wecloud.im.netty.handler;
import
com.alibaba.fastjson.JSONObject
;
import
com.auth0.jwt.interfaces.DecodedJWT
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.netty.core.WsReadHandler
;
import
com.wecloud.im.ws.model.WsConstants
;
import
com.wecloud.im.ws.service.MangerChannelService
;
import
com.wecloud.im.ws.utils.FullHttpRequestUtils
;
import
com.wecloud.utils.JsonUtils
;
import
io.geekidea.springbootplus.config.constant.CommonConstant
;
import
io.geekidea.springbootplus.framework.common.api.ApiCode
;
import
io.geekidea.springbootplus.framework.common.api.ApiResult
;
...
...
@@ -56,7 +56,7 @@ public class NettyApiRequest {
*/
public
void
handle
(
ChannelHandlerContext
ctx
,
Object
msg
,
FullHttpRequest
httpRequest
)
throws
Exception
{
if
(!(
msg
instanceof
FullHttpRequest
))
{
String
context
=
new
JsonMapper
().
writeValueAsString
(
ApiResult
.
fail
());
String
context
=
JsonUtils
.
encodeJson
(
ApiResult
.
fail
());
FullHttpRequestUtils
.
send
(
ctx
,
context
,
HttpResponseStatus
.
OK
);
return
;
}
...
...
@@ -83,13 +83,13 @@ public class NettyApiRequest {
Map
<
String
,
String
>
paramMap
=
FullHttpRequestUtils
.
parameterParse
(
httpRequest
);
String
token
=
paramMap
.
get
(
WsConstants
.
TOKEN
);
if
(
StringUtils
.
isBlank
(
token
))
{
String
context
=
new
JsonMapper
().
writeValueAsString
(
ApiResult
.
result
(
ApiCode
.
FAIL
,
"token不能为空"
,
(
Object
)
null
));
String
context
=
JsonUtils
.
encodeJson
(
ApiResult
.
result
(
ApiCode
.
FAIL
,
"token不能为空"
,
(
Object
)
null
));
FullHttpRequestUtils
.
send
(
ctx
,
context
,
HttpResponseStatus
.
OK
);
return
;
}
if
(
JwtUtil
.
isExpired
(
token
))
{
String
context
=
new
JsonMapper
().
writeValueAsString
(
ApiResult
.
result
(
ApiCode
.
FAIL
,
"JWT Token已过期,token"
,
(
Object
)
null
));
String
context
=
JsonUtils
.
encodeJson
(
ApiResult
.
result
(
ApiCode
.
FAIL
,
"JWT Token已过期,token"
,
(
Object
)
null
));
FullHttpRequestUtils
.
send
(
ctx
,
context
,
HttpResponseStatus
.
OK
);
return
;
}
...
...
@@ -108,14 +108,14 @@ public class NettyApiRequest {
if
(
jwtToken
==
null
)
{
log
.
info
(
"jwtToken == null ,token和redis不一致, clientId:"
+
clientId
+
",token:"
+
token
);
String
context
=
new
JsonMapper
().
writeValueAsString
(
ApiResult
.
result
(
ApiCode
.
FAIL
,
"jwtToken == null ,token和redis不一致"
,
(
Object
)
null
));
String
context
=
JsonUtils
.
encodeJson
(
ApiResult
.
result
(
ApiCode
.
FAIL
,
"jwtToken == null ,token和redis不一致"
,
(
Object
)
null
));
FullHttpRequestUtils
.
send
(
ctx
,
context
,
HttpResponseStatus
.
OK
);
return
;
}
if
((!
jwtToken
.
getClientId
().
equals
(
clientId
))
||
(!
jwtToken
.
getAppKey
().
equals
(
appKey
)))
{
log
.
info
(
"clientId appKey 不一致"
);
String
context
=
new
JsonMapper
().
writeValueAsString
(
ApiResult
.
result
(
ApiCode
.
FAIL
,
"clientId appKey 不一致"
,
(
Object
)
null
));
String
context
=
JsonUtils
.
encodeJson
(
ApiResult
.
result
(
ApiCode
.
FAIL
,
"clientId appKey 不一致"
,
(
Object
)
null
));
FullHttpRequestUtils
.
send
(
ctx
,
context
,
HttpResponseStatus
.
OK
);
return
;
}
...
...
core/src/main/java/com/wecloud/im/param/add/ImMsgRecall.java
View file @
60b245ba
package
com
.
wecloud
.
im
.
param
.
add
;
import
com.wecloud.im.ws.model.request.Push
Model
;
import
com.wecloud.im.ws.model.request.Push
VO
;
import
io.geekidea.springbootplus.framework.common.entity.BaseEntity
;
import
io.swagger.annotations.ApiModel
;
import
io.swagger.annotations.ApiModelProperty
;
...
...
@@ -25,6 +25,6 @@ public class ImMsgRecall extends BaseEntity {
private
Long
msgId
;
@ApiModelProperty
(
"自定义推送字段"
)
private
Push
Model
push
;
private
Push
VO
push
;
}
core/src/main/java/com/wecloud/im/service/ImConversationService.java
View file @
60b245ba
...
...
@@ -42,7 +42,7 @@ public interface ImConversationService extends BaseService<ImConversation> {
* @param imConversationCreate
* @return
*/
ApiResult
<
ImConversationCreateVo
>
createImConversation
(
ImConversationCreate
imConversationCreate
)
throws
JsonProcessingException
;
ApiResult
<
ImConversationCreateVo
>
createImConversation
(
ImConversationCreate
imConversationCreate
);
/**
...
...
core/src/main/java/com/wecloud/im/service/ImMessageService.java
View file @
60b245ba
...
...
@@ -9,6 +9,7 @@ import com.wecloud.im.param.add.ImMsgSendToOnlineClient;
import
com.wecloud.im.param.add.ImMsgUpdate
;
import
com.wecloud.im.vo.ImMessageOfflineListVo
;
import
com.wecloud.im.vo.OfflineMsgDto
;
import
com.wecloud.im.ws.model.request.ReceiveDataVO
;
import
io.geekidea.springbootplus.framework.common.api.ApiResult
;
import
io.geekidea.springbootplus.framework.common.service.BaseService
;
import
io.geekidea.springbootplus.framework.core.pagination.Paging
;
...
...
@@ -33,7 +34,7 @@ public interface ImMessageService extends BaseService<ImMessage> {
ApiResult
<
Boolean
>
restApiImMessageSend
(
ImMsgSendToOnlineClient
imMsgSendToOnlineClient
,
ImApplication
imApplication
);
ImMessage
saveImMessage
(
ImApplication
imApplication
,
ImClient
imClientSender
,
Long
toConversationId
,
long
messageId
,
String
content
);
ImMessage
saveImMessage
(
ImApplication
imApplication
,
ImClient
imClientSender
,
Long
toConversationId
,
long
messageId
,
ReceiveDataVO
content
);
/**
...
...
core/src/main/java/com/wecloud/im/service/impl/ImConversationMembersServiceImpl.java
View file @
60b245ba
...
...
@@ -4,8 +4,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import
com.baomidou.mybatisplus.core.metadata.IPage
;
import
com.baomidou.mybatisplus.core.metadata.OrderItem
;
import
com.baomidou.mybatisplus.extension.plugins.pagination.Page
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.entity.ImApplication
;
import
com.wecloud.im.entity.ImClient
;
import
com.wecloud.im.entity.ImConversationMembers
;
...
...
@@ -25,6 +23,7 @@ import com.wecloud.im.service.ImConversationService;
import
com.wecloud.im.service.ImMessageService
;
import
com.wecloud.im.vo.ImConversationMemberListVo
;
import
com.wecloud.im.ws.service.WriteDataService
;
import
com.wecloud.utils.JsonUtils
;
import
io.geekidea.springbootplus.framework.common.api.ApiResult
;
import
io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl
;
import
io.geekidea.springbootplus.framework.core.pagination.PageInfo
;
...
...
@@ -48,9 +47,6 @@ import java.util.List;
@Service
public
class
ImConversationMembersServiceImpl
extends
BaseServiceImpl
<
ImConversationMembersMapper
,
ImConversationMembers
>
implements
ImConversationMembersService
{
// private static final JsonMapper JSON_MAPPER = new JsonMapper();
@Autowired
private
WriteDataService
writeDataService
;
...
...
@@ -170,17 +166,9 @@ public class ImConversationMembersServiceImpl extends BaseServiceImpl<ImConversa
// .notIn(ImConversationMembers::getId, imClientSender.getId())
// );
JsonMapper
jsonMapper
=
new
JsonMapper
();
try
{
String
attributes
=
jsonMapper
.
writeValueAsString
(
imConversationMemAttrUpdate
.
getAttributes
());
String
attributes
=
JsonUtils
.
encodeJson
(
imConversationMemAttrUpdate
.
getAttributes
());
imConversationMember
.
setAttributes
(
attributes
);
imConversationMember
.
setAttributes
(
attributes
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
return
ApiResult
.
fail
();
}
boolean
b
=
imConversationMembersService
.
updateById
(
imConversationMember
);
if
(
b
)
{
...
...
core/src/main/java/com/wecloud/im/service/impl/ImConversationServiceImpl.java
View file @
60b245ba
...
...
@@ -5,8 +5,6 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import
com.baomidou.mybatisplus.core.metadata.IPage
;
import
com.baomidou.mybatisplus.core.metadata.OrderItem
;
import
com.baomidou.mybatisplus.extension.plugins.pagination.Page
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.entity.ImApplication
;
import
com.wecloud.im.entity.ImClient
;
import
com.wecloud.im.entity.ImConversation
;
...
...
@@ -34,6 +32,7 @@ import com.wecloud.im.ws.enums.MsgTypeEnum;
import
com.wecloud.im.ws.enums.WsResponseCmdEnum
;
import
com.wecloud.im.ws.model.WsResponseModel
;
import
com.wecloud.im.ws.service.WriteDataService
;
import
com.wecloud.utils.JsonUtils
;
import
io.geekidea.springbootplus.framework.common.api.ApiCode
;
import
io.geekidea.springbootplus.framework.common.api.ApiResult
;
import
io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl
;
...
...
@@ -63,9 +62,6 @@ import java.util.Map;
@Service
public
class
ImConversationServiceImpl
extends
BaseServiceImpl
<
ImConversationMapper
,
ImConversation
>
implements
ImConversationService
{
private
static
final
JsonMapper
JSON_MAPPER
=
new
JsonMapper
();
@Autowired
private
WriteDataService
writeDataService
;
...
...
@@ -89,13 +85,13 @@ public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMap
@Transactional
(
rollbackFor
=
Exception
.
class
)
@Override
public
boolean
saveImConversation
(
ImConversation
imConversation
)
throws
Exception
{
public
boolean
saveImConversation
(
ImConversation
imConversation
)
{
return
super
.
save
(
imConversation
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
ApiResult
<
ImConversationCreateVo
>
createImConversation
(
ImConversationCreate
imConversationCreate
)
throws
JsonProcessingException
{
public
ApiResult
<
ImConversationCreateVo
>
createImConversation
(
ImConversationCreate
imConversationCreate
)
{
ImClient
createClient
=
imClientService
.
getCurentClient
();
...
...
@@ -152,8 +148,7 @@ public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMap
ImClient
inviteClient
=
imClientService
.
getOne
(
new
QueryWrapper
<
ImClient
>().
lambda
()
.
eq
(
ImClient:
:
getFkAppid
,
createClient
.
getFkAppid
())
.
eq
(
ImClient:
:
getClientId
,
imConversationCreate
.
getClientIds
().
get
(
0
)));
JsonMapper
jsonMapper
=
new
JsonMapper
();
String
asString
=
jsonMapper
.
writeValueAsString
(
imConversationCreate
.
getAttributes
());
String
asString
=
JsonUtils
.
encodeJson
(
imConversationCreate
.
getAttributes
());
log
.
info
(
"RequestAttributes:"
+
asString
);
...
...
@@ -186,10 +181,10 @@ public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMap
imConversation
.
setCreator
(
creator
);
imConversation
.
setName
(
imConversationCreate
.
getName
());
imConversation
.
setSystemFlag
(
false
);
JsonMapper
jsonMapper
=
new
JsonMapper
();
// 拓展数据
String
writeValueAsString
=
jsonMapper
.
writeValueAsString
(
imConversationCreate
.
getAttributes
());
imConversation
.
setAttributes
(
writeValueAsString
);
String
attributesStr
=
JsonUtils
.
encodeJson
(
imConversationCreate
.
getAttributes
());
imConversation
.
setAttributes
(
attributesStr
);
imConversationService
.
save
(
imConversation
);
// 将创建者自己添加到会话
...
...
@@ -286,12 +281,7 @@ public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMap
content
.
put
(
"operator"
,
imClientSender
.
getClientId
());
//操作的client ID
content
.
put
(
"passivityOperator"
,
client2
.
getClientId
());
//被操作的client ID
content
.
put
(
"type"
,
MsgTypeEnum
.
INVITE_CLIENT_JOIN_CONVERSATION
.
getUriCode
());
//xx邀请xx加入会话 -1007
try
{
String
contentString
=
JSON_MAPPER
.
writeValueAsString
(
content
);
imMessage
.
setContent
(
contentString
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
}
imMessage
.
setContent
(
JsonUtils
.
encodeJson
(
content
));
// 保存消息至消息表
imMessage
.
setId
(
messageId
);
...
...
@@ -402,13 +392,7 @@ public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMap
content
.
put
(
"operator"
,
imClientSender
.
getClientId
());
//操作的client ID
content
.
put
(
"passivityOperator"
,
client2
.
getClientId
());
//被操作的client ID
content
.
put
(
"type"
,
MsgTypeEnum
.
REMOVE_CLIENT_CONVERSATION
.
getUriCode
());
//xx被xx移出会话 -1008
try
{
String
asString
=
JSON_MAPPER
.
writeValueAsString
(
content
);
imMessage
.
setContent
(
asString
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
}
imMessage
.
setContent
(
JsonUtils
.
encodeJson
(
content
));
// 保存消息至消息表
imMessage
.
setId
(
messageId
);
...
...
@@ -511,13 +495,8 @@ public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMap
Map
<
String
,
Object
>
content
=
new
HashMap
<>();
content
.
put
(
"type"
,
MsgTypeEnum
.
LEAVE_CONVERSATION
.
getUriCode
());
// xx主动退出会话
try
{
String
asString
=
JSON_MAPPER
.
writeValueAsString
(
content
);
imMessage
.
setContent
(
asString
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
}
String
asString
=
JsonUtils
.
encodeJson
(
content
);;
imMessage
.
setContent
(
asString
);
// 保存消息至消息表
imMessage
.
setId
(
messageId
);
...
...
@@ -687,16 +666,8 @@ public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMap
.
notIn
(
ImConversationMembers:
:
getId
,
imClientSender
.
getId
())
);
JsonMapper
jsonMapper
=
new
JsonMapper
();
try
{
String
attributes
=
jsonMapper
.
writeValueAsString
(
imConversationAttrUpdate
.
getAttributes
());
imConversationById
.
setAttributes
(
attributes
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
return
ApiResult
.
fail
();
}
String
attributes
=
JsonUtils
.
encodeJson
(
imConversationAttrUpdate
.
getAttributes
());
imConversationById
.
setAttributes
(
attributes
);
boolean
b
=
imConversationService
.
updateById
(
imConversationById
);
if
(
b
)
{
...
...
@@ -800,14 +771,13 @@ public class ImConversationServiceImpl extends BaseServiceImpl<ImConversationMap
// 查询用户加入的所有会话 与每个会话的未读条数 成员
List
<
MyConversationListVo
>
myImConversationListAndMsgCount
=
imConversationMapper
.
getMyImConversationListAndMsgCount
(
client
.
getId
());
JsonMapper
jsonMapper
=
new
JsonMapper
();
// 返回的
List
<
MyConversationListVo
>
myImConversationListAndMsgCountNew
=
new
ArrayList
<>();
// 转换json格式
for
(
MyConversationListVo
myconversationlistvo
:
myImConversationListAndMsgCount
)
{
HashMap
attributess
=
jsonMapper
.
readValue
(
myconversationlistvo
.
getAttribute
(),
HashMap
.
class
);
HashMap
attributess
=
JsonUtils
.
json2Map
(
myconversationlistvo
.
getAttribute
()
);
myconversationlistvo
.
setAttributes
(
attributess
);
// 查询会话的最后一条消息
...
...
core/src/main/java/com/wecloud/im/service/impl/ImMessageServiceImpl.java
View file @
60b245ba
...
...
@@ -4,8 +4,6 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import
com.baomidou.mybatisplus.core.metadata.IPage
;
import
com.baomidou.mybatisplus.core.metadata.OrderItem
;
import
com.baomidou.mybatisplus.extension.plugins.pagination.Page
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.entity.ImApiMessageOnlineSend
;
import
com.wecloud.im.entity.ImApplication
;
import
com.wecloud.im.entity.ImClient
;
...
...
@@ -27,9 +25,11 @@ import com.wecloud.im.vo.ImMessageOfflineListVo;
import
com.wecloud.im.vo.OfflineMsgDto
;
import
com.wecloud.im.ws.enums.WsResponseCmdEnum
;
import
com.wecloud.im.ws.model.WsResponseModel
;
import
com.wecloud.im.ws.model.request.PushModel
;
import
com.wecloud.im.ws.model.request.PushVO
;
import
com.wecloud.im.ws.model.request.ReceiveDataVO
;
import
com.wecloud.im.ws.sender.AsyncPush
;
import
com.wecloud.im.ws.service.WriteDataService
;
import
com.wecloud.utils.JsonUtils
;
import
io.geekidea.springbootplus.framework.common.api.ApiCode
;
import
io.geekidea.springbootplus.framework.common.api.ApiResult
;
import
io.geekidea.springbootplus.framework.common.service.impl.BaseServiceImpl
;
...
...
@@ -55,8 +55,6 @@ import java.util.List;
@Service
public
class
ImMessageServiceImpl
extends
BaseServiceImpl
<
ImMessageMapper
,
ImMessage
>
implements
ImMessageService
{
// private static final JsonMapper JSON_MAPPER = new JsonMapper();
@Autowired
private
ImMessageMapper
imMessageMapper
;
...
...
@@ -99,16 +97,9 @@ public class ImMessageServiceImpl extends BaseServiceImpl<ImMessageMapper, ImMes
ImApiMessageOnlineSend
imApiMessageOnlineSend
=
new
ImApiMessageOnlineSend
();
imApiMessageOnlineSend
.
setCreateTime
(
new
Date
());
JsonMapper
jsonMapper
=
new
JsonMapper
();
try
{
String
attributes
=
jsonMapper
.
writeValueAsString
(
imMsgSendToOnlineClient
.
getContent
());
imApiMessageOnlineSend
.
setContent
(
attributes
);
String
attributes
=
JsonUtils
.
encodeJson
(
imMsgSendToOnlineClient
.
getContent
());
imApiMessageOnlineSend
.
setContent
(
attributes
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
return
ApiResult
.
fail
();
}
imApiMessageOnlineSend
.
setConversationId
(
imMsgSendToOnlineClient
.
getConversationId
());
...
...
@@ -141,15 +132,15 @@ public class ImMessageServiceImpl extends BaseServiceImpl<ImMessageMapper, ImMes
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
ImMessage
saveImMessage
(
ImApplication
imApplication
,
ImClient
imClientSender
,
Long
toConversationId
,
long
messageId
,
String
content
)
{
public
ImMessage
saveImMessage
(
ImApplication
imApplication
,
ImClient
imClientSender
,
Long
toConversationId
,
long
messageId
,
ReceiveDataVO
content
)
{
ImMessage
imMessage
=
new
ImMessage
();
imMessage
.
setId
(
messageId
);
imMessage
.
setCreateTime
(
new
Date
());
imMessage
.
setFkAppid
(
imApplication
.
getId
());
imMessage
.
setSender
(
imClientSender
.
getId
());
imMessage
.
setContent
(
content
);
String
contentStr
=
JsonUtils
.
encodeJson
(
content
);
imMessage
.
setContent
(
contentStr
);
imMessage
.
setWithdraw
(
false
);
imMessage
.
setEvent
(
false
);
imMessage
.
setSystemFlag
(
false
);
...
...
@@ -246,10 +237,10 @@ public class ImMessageServiceImpl extends BaseServiceImpl<ImMessageMapper, ImMes
writeDataService
.
write
(
responseModel
,
imApplication
.
getAppKey
(),
imClientReceiver
.
getClientId
());
// 获取自定义推送字段
Push
Model
pushModel
=
imMsgRecall
.
getPush
();
Push
VO
pushVO
=
imMsgRecall
.
getPush
();
// 异步推送系统通知消息
asyncPush
.
push
(
push
Model
,
imClientReceiver
,
imApplication
);
asyncPush
.
push
(
push
VO
,
imClientReceiver
,
imApplication
);
}
return
ApiResult
.
ok
();
...
...
@@ -275,15 +266,8 @@ public class ImMessageServiceImpl extends BaseServiceImpl<ImMessageMapper, ImMes
ImMessage
imMessage
=
new
ImMessage
();
imMessage
.
setId
(
imMsgUpdate
.
getMsgId
());
JsonMapper
jsonMapper
=
new
JsonMapper
();
try
{
String
content
=
jsonMapper
.
writeValueAsString
(
imMsgUpdate
.
getContent
());
imMessage
.
setContent
(
content
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
return
ApiResult
.
fail
();
}
String
content
=
JsonUtils
.
encodeJson
(
imMsgUpdate
.
getContent
());
imMessage
.
setContent
(
content
);
if
(
this
.
updateById
(
imMessage
))
{
return
ApiResult
.
ok
();
...
...
core/src/main/java/com/wecloud/im/ws/model/request/Push
Model
.java
→
core/src/main/java/com/wecloud/im/ws/model/request/Push
VO
.java
View file @
60b245ba
...
...
@@ -10,7 +10,7 @@ import java.io.Serializable;
* @Date 2019-12-05
*/
@Data
public
class
Push
Model
implements
Serializable
{
public
class
Push
VO
implements
Serializable
{
/**
* 标题
...
...
core/src/main/java/com/wecloud/im/ws/model/request/ReceiveDataVO.java
0 → 100644
View file @
60b245ba
package
com
.
wecloud
.
im
.
ws
.
model
.
request
;
import
lombok.Data
;
import
java.io.Serializable
;
import
java.util.HashMap
;
@Data
public
class
ReceiveDataVO
implements
Serializable
{
/**
* push 对象
*/
private
PushVO
push
;
/**
* 自定义的值
*/
private
String
diyAbcd
;
/**
* 发送的会话id
*/
private
Long
toConversation
;
/**
* 发送的type
*/
private
Integer
type
;
/**
* 发送的内容文本
*/
private
String
text
;
/**
* 自定义可扩展的发送字段和值
*/
private
HashMap
attrs
;
}
core/src/main/java/com/wecloud/im/ws/model/request/Receive
Model
.java
→
core/src/main/java/com/wecloud/im/ws/model/request/Receive
VO
.java
View file @
60b245ba
package
com
.
wecloud
.
im
.
ws
.
model
.
request
;
import
com.wecloud.im.ws.enums.WsRequestCmdEnum
;
import
lombok.AllArgsConstructor
;
import
lombok.Data
;
import
lombok.NoArgsConstructor
;
...
...
@@ -15,10 +16,10 @@ import java.util.HashMap;
@Data
@NoArgsConstructor
@AllArgsConstructor
public
class
Receive
Model
implements
Serializable
{
public
class
Receive
VO
implements
Serializable
{
/**
* 枚举类
UriPathEnum
请求uri的编码
* 枚举类
{@link WsRequestCmdEnum }
请求uri的编码
* 由于websocket使用同一个通道发送数据,需要区分不同类型请求
*/
private
Integer
cmd
;
...
...
@@ -26,7 +27,7 @@ public class ReceiveModel implements Serializable {
/**
* json数据
*/
private
HashMap
data
;
private
ReceiveDataVO
data
;
/**
* 请求id, 以判空是否请求成功, 服务端处理完成后 返回此id
...
...
core/src/main/java/com/wecloud/im/ws/receive/WsDataReader.java
deleted
100644 → 0
View file @
665de18a
package
com
.
wecloud
.
im
.
ws
.
receive
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.ws.enums.WsRequestCmdEnum
;
import
com.wecloud.im.ws.model.request.ReceiveModel
;
import
com.wecloud.im.ws.service.WriteDataService
;
import
com.wecloud.im.ws.strategy.AbstractImCmdStrategy
;
import
com.wecloud.im.ws.strategy.ImCmdStrategyFactory
;
import
io.geekidea.springbootplus.framework.common.exception.BusinessException
;
import
io.netty.channel.ChannelHandlerContext
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.stereotype.Service
;
import
javax.annotation.Resource
;
/**
* @Description ws 数据接收 转换类
* @Author hewei hwei1233@163.com
* @Date 2019-12-03
*/
@Service
public
class
WsDataReader
{
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
WsDataReader
.
class
);
@Resource
private
ImCmdStrategyFactory
receiveStrategyContext
;
@Resource
private
WriteDataService
writeDataService
;
/**
* 在此开始进入业务流程子线程,将不占netty的io线程
*
* @param data
* @throws Exception
*/
public
void
convertModel
(
String
data
,
ChannelHandlerContext
ctx
,
String
appKey
,
String
clientId
)
throws
Exception
{
log
.
info
(
"appWS收到data:"
+
data
+
"\nappKey+clientId:"
+
appKey
+
":"
+
clientId
+
",channelId:"
+
ctx
.
channel
().
id
().
asLongText
());
// 解析json
JsonMapper
jsonMapper
=
new
JsonMapper
();
ReceiveModel
receiveModel
=
jsonMapper
.
readValue
(
data
,
ReceiveModel
.
class
);
if
(
null
==
receiveModel
||
null
==
receiveModel
.
getCmd
())
{
throw
new
BusinessException
(
"null == receiveModel || null == receiveModel.getCmd()"
);
}
WsRequestCmdEnum
wsRequestUriPathEnum
=
WsRequestCmdEnum
.
getByCode
(
receiveModel
.
getCmd
());
// 使用策略模式, 根据不同类型请求调用不同实现类
AbstractImCmdStrategy
cmdStrategy
=
receiveStrategyContext
.
getStrategy
(
wsRequestUriPathEnum
);
cmdStrategy
.
process
(
receiveModel
,
ctx
,
data
,
appKey
,
clientId
);
}
}
core/src/main/java/com/wecloud/im/ws/sender/AsyncPush.java
View file @
60b245ba
...
...
@@ -9,7 +9,7 @@ import com.wecloud.im.entity.ImIosApns;
import
com.wecloud.im.push.PushUtils
;
import
com.wecloud.im.service.ImInboxService
;
import
com.wecloud.im.service.ImIosApnsService
;
import
com.wecloud.im.ws.model.request.Push
Model
;
import
com.wecloud.im.ws.model.request.Push
VO
;
import
lombok.extern.slf4j.Slf4j
;
import
org.json.JSONObject
;
import
org.springframework.beans.factory.annotation.Autowired
;
...
...
@@ -58,13 +58,13 @@ public class AsyncPush {
* @param imClientReceiver
*/
@Async
public
void
push
(
Push
Model
pushModel
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
public
void
push
(
Push
VO
pushVO
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
log
.
info
(
"push:"
+
imClientReceiver
.
getClientId
());
if
(
push
Model
==
null
)
{
push
Model
=
new
PushModel
();
push
Model
.
setTitle
(
PUSH_TITLE
);
push
Model
.
setSubTitle
(
PUSH_BODY
);
if
(
push
VO
==
null
)
{
push
VO
=
new
PushVO
();
push
VO
.
setTitle
(
PUSH_TITLE
);
push
VO
.
setSubTitle
(
PUSH_BODY
);
}
// 校验参数
...
...
@@ -80,10 +80,10 @@ public class AsyncPush {
// 设备类型1:ios; 2:android
if
(
imClientReceiver
.
getDeviceType
()
==
1
)
{
ios
(
push
Model
,
imClientReceiver
,
imApplication
);
ios
(
push
VO
,
imClientReceiver
,
imApplication
);
}
else
{
android
(
push
Model
,
imClientReceiver
,
imApplication
);
android
(
push
VO
,
imClientReceiver
,
imApplication
);
}
}
...
...
@@ -97,21 +97,21 @@ public class AsyncPush {
public
void
push
(
HashMap
<
String
,
String
>
pushMap
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
log
.
info
(
"push:"
+
imClientReceiver
.
getClientId
());
Push
Model
pushModel
=
new
PushModel
();
Push
VO
pushVO
=
new
PushVO
();
if
(
pushMap
==
null
||
pushMap
.
isEmpty
())
{
push
Model
.
setTitle
(
PUSH_TITLE
);
push
Model
.
setSubTitle
(
PUSH_BODY
);
push
VO
.
setTitle
(
PUSH_TITLE
);
push
VO
.
setSubTitle
(
PUSH_BODY
);
}
else
{
push
Model
.
setTitle
(
pushMap
.
get
(
TITLE
));
push
Model
.
setSubTitle
(
pushMap
.
get
(
SUB_TITLE
));
push
VO
.
setTitle
(
pushMap
.
get
(
TITLE
));
push
VO
.
setSubTitle
(
pushMap
.
get
(
SUB_TITLE
));
}
this
.
push
(
push
Model
,
imClientReceiver
,
imApplication
);
this
.
push
(
push
VO
,
imClientReceiver
,
imApplication
);
}
private
void
android
(
Push
Model
pushModel
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
private
void
android
(
Push
VO
pushVO
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
if
(
imApplication
.
getAndroidPushChannel
()
==
null
)
{
return
;
...
...
@@ -127,7 +127,7 @@ public class AsyncPush {
// 安卓 单推
String
deviceToken
=
imClientReceiver
.
getDeviceToken
();
try
{
pushUtils
.
sendIOSUnicast
(
deviceToken
,
push
Model
.
getTitle
(),
pushModel
.
getSubTitle
(),
PUSH_BODY
);
pushUtils
.
sendIOSUnicast
(
deviceToken
,
push
VO
.
getTitle
(),
pushVO
.
getSubTitle
(),
PUSH_BODY
);
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
...
...
@@ -137,7 +137,7 @@ public class AsyncPush {
//firebase:2
log
.
info
(
"android_firebase"
);
firebase
(
push
Model
,
imClientReceiver
,
imApplication
);
firebase
(
push
VO
,
imClientReceiver
,
imApplication
);
}
else
if
(
imApplication
.
getAndroidPushChannel
()
==
3
)
{
// 信鸽3
...
...
@@ -149,7 +149,7 @@ public class AsyncPush {
}
}
private
void
ios
(
Push
Model
pushModel
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
private
void
ios
(
Push
VO
pushVO
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
if
(
imApplication
.
getIosPushChannel
()
==
null
)
{
return
;
...
...
@@ -165,9 +165,9 @@ public class AsyncPush {
// 安卓单推
String
deviceToken
=
imClientReceiver
.
getDeviceToken
();
String
unicastText
=
"Android unicast text"
;
String
unicastTicker
=
push
Model
.
getSubTitle
();
String
unicastTicker
=
push
VO
.
getSubTitle
();
try
{
pushUtils
.
sendAndroidUnicast
(
deviceToken
,
unicastText
,
unicastTicker
,
push
Model
.
getTitle
());
pushUtils
.
sendAndroidUnicast
(
deviceToken
,
unicastText
,
unicastTicker
,
push
VO
.
getTitle
());
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
...
...
@@ -178,20 +178,20 @@ public class AsyncPush {
log
.
info
(
"firebase"
);
firebase
(
push
Model
,
imClientReceiver
,
imApplication
);
firebase
(
push
VO
,
imClientReceiver
,
imApplication
);
}
else
if
(
imApplication
.
getIosPushChannel
()
==
3
)
{
// apns原生:3
log
.
info
(
"apns原生"
);
apnsPush
(
push
Model
,
imClientReceiver
,
imApplication
);
apnsPush
(
push
VO
,
imClientReceiver
,
imApplication
);
}
else
{
log
.
info
(
"没有找到推送类型"
);
}
}
public
void
firebase
(
Push
Model
pushModel
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
public
void
firebase
(
Push
VO
pushVO
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
String
jsonStr
=
null
;
try
{
URL
url
=
new
URL
(
API_URL_FCM
);
...
...
@@ -208,8 +208,8 @@ public class AsyncPush {
//推送到哪台客户端机器
json
.
put
(
"to"
,
imClientReceiver
.
getDeviceToken
());
JSONObject
info
=
new
JSONObject
();
info
.
put
(
"title"
,
push
Model
.
getTitle
());
info
.
put
(
"body"
,
push
Model
.
getSubTitle
());
info
.
put
(
"title"
,
push
VO
.
getTitle
());
info
.
put
(
"body"
,
push
VO
.
getSubTitle
());
//数据消息data 通知消息 notification
json
.
put
(
"notification"
,
info
);
...
...
@@ -232,13 +232,13 @@ public class AsyncPush {
}
}
private
void
apnsPush
(
Push
Model
pushModel
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
private
void
apnsPush
(
Push
VO
pushVO
,
ImClient
imClientReceiver
,
ImApplication
imApplication
)
{
// 查询apns证书
ImIosApns
apns
=
imIosApnsService
.
getImIosApnsByAppId
(
imApplication
.
getId
());
Map
<
String
,
Object
>
customProperty
=
new
HashMap
<
String
,
Object
>(
1
);
String
deviceToken
=
imClientReceiver
.
getDeviceToken
();
String
alertTitle
=
push
Model
.
getTitle
();
String
alertBody
=
push
Model
.
getSubTitle
();
String
alertTitle
=
push
VO
.
getTitle
();
String
alertBody
=
push
VO
.
getSubTitle
();
// 统计未读消息数量
int
badge
=
imInboxService
.
countMyNotReadCount
(
imClientReceiver
.
getId
());
String
topicBundleId
=
apns
.
getBundleId
();
...
...
core/src/main/java/com/wecloud/im/ws/service/WriteDataService.java
View file @
60b245ba
...
...
@@ -2,7 +2,7 @@ package com.wecloud.im.ws.service;
import
com.wecloud.im.ws.model.WsResponseModel
;
import
com.wecloud.im.ws.model.request.Receive
Model
;
import
com.wecloud.im.ws.model.request.Receive
VO
;
import
io.geekidea.springbootplus.framework.common.api.ApiCode
;
import
io.netty.channel.socket.nio.NioSocketChannel
;
...
...
@@ -16,10 +16,10 @@ public interface WriteDataService {
/**
* 可自定义状态码 带data
*
* @param receive
Model
* @param receive
VO
* @param data
*/
void
dataAndStatus
(
Receive
Model
receiveModel
,
ApiCode
apiCode
,
Object
data
,
String
toAppKey
,
String
toClientId
);
void
dataAndStatus
(
Receive
VO
receiveVO
,
ApiCode
apiCode
,
Object
data
,
String
toAppKey
,
String
toClientId
);
/**
* 固定"成功"状态码 带data
...
...
@@ -27,21 +27,21 @@ public interface WriteDataService {
* @param requestModel
* @param data
*/
void
successAndData
(
Receive
Model
requestModel
,
Object
data
,
String
toAppKey
,
String
toClientId
);
void
successAndData
(
Receive
VO
requestModel
,
Object
data
,
String
toAppKey
,
String
toClientId
);
/**
* 固定"成功"状态码 无data
*
* @param requestModel
*/
void
nullDataSuccess
(
Receive
Model
requestModel
,
ApiCode
apiCode
,
String
toAppKey
,
String
toClientId
);
void
nullDataSuccess
(
Receive
VO
requestModel
,
ApiCode
apiCode
,
String
toAppKey
,
String
toClientId
);
/**
* 固定"参数错误"状态码 无data
*
* @param requestModel
*/
void
paramErrorAndNullData
(
Receive
Model
requestModel
,
String
toAppKey
,
String
toClientId
);
void
paramErrorAndNullData
(
Receive
VO
requestModel
,
String
toAppKey
,
String
toClientId
);
/**
* 调用ws处理响应逻辑
...
...
core/src/main/java/com/wecloud/im/ws/service/impl/WriteDataServiceImpl.java
View file @
60b245ba
package
com
.
wecloud
.
im
.
ws
.
service
.
impl
;
import
cn.hutool.core.thread.ThreadFactoryBuilder
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.router.RouterSendService
;
import
com.wecloud.im.ws.cache.UserCacheService
;
import
com.wecloud.im.ws.model.WsResponseModel
;
import
com.wecloud.im.ws.model.redis.ClientChannelInfo
;
import
com.wecloud.im.ws.model.request.Receive
Model
;
import
com.wecloud.im.ws.model.request.Receive
VO
;
import
com.wecloud.im.ws.service.MangerChannelService
;
import
com.wecloud.im.ws.service.WriteDataService
;
import
com.wecloud.im.ws.utils.InitIp
;
import
com.wecloud.utils.JsonUtils
;
import
io.geekidea.springbootplus.framework.common.api.ApiCode
;
import
io.geekidea.springbootplus.framework.common.api.ApiResult
;
import
io.netty.channel.socket.nio.NioSocketChannel
;
...
...
@@ -53,61 +52,38 @@ public class WriteDataServiceImpl implements WriteDataService {
private
RouterSendService
routerSendService
;
@Override
public
void
successAndData
(
Receive
Model
receiveModel
,
Object
data
,
String
toAppKey
,
String
toClientId
)
{
this
.
dataAndStatus
(
receive
Model
,
ApiCode
.
SUCCESS
,
data
,
toAppKey
,
toClientId
);
public
void
successAndData
(
Receive
VO
receiveVO
,
Object
data
,
String
toAppKey
,
String
toClientId
)
{
this
.
dataAndStatus
(
receive
VO
,
ApiCode
.
SUCCESS
,
data
,
toAppKey
,
toClientId
);
}
@Override
public
void
nullDataSuccess
(
Receive
Model
receiveModel
,
ApiCode
apiCode
,
String
toAppKey
,
String
toClientId
)
{
this
.
dataAndStatus
(
receive
Model
,
apiCode
,
new
HashMap
<>(
1
),
toAppKey
,
toClientId
);
public
void
nullDataSuccess
(
Receive
VO
receiveVO
,
ApiCode
apiCode
,
String
toAppKey
,
String
toClientId
)
{
this
.
dataAndStatus
(
receive
VO
,
apiCode
,
new
HashMap
<>(
1
),
toAppKey
,
toClientId
);
}
@Override
public
void
paramErrorAndNullData
(
Receive
Model
receiveModel
,
String
toAppKey
,
String
toClientId
)
{
public
void
paramErrorAndNullData
(
Receive
VO
receiveVO
,
String
toAppKey
,
String
toClientId
)
{
// this.nullDataSuccess(requestModel, ResultStatus.PARAM_ERROR, userId);
}
@Override
public
void
dataAndStatus
(
Receive
Model
receiveModel
,
ApiCode
apiCode
,
Object
data
,
String
toAppKey
,
String
toClientId
)
{
public
void
dataAndStatus
(
Receive
VO
receiveVO
,
ApiCode
apiCode
,
Object
data
,
String
toAppKey
,
String
toClientId
)
{
ApiResult
<
Boolean
>
apiResult
=
ApiResult
.
result
(
apiCode
);
WsResponseModel
responseModel
=
new
WsResponseModel
();
responseModel
.
setMsg
(
apiResult
.
getMessage
());
responseModel
.
setCmd
(
receive
Model
.
getCmd
());
responseModel
.
setReqId
(
receive
Model
.
getReqId
());
responseModel
.
setCmd
(
receive
VO
.
getCmd
());
responseModel
.
setReqId
(
receive
VO
.
getReqId
());
responseModel
.
setData
(
data
);
responseModel
.
setCode
(
apiResult
.
getCode
());
this
.
write
(
responseModel
,
toAppKey
,
toClientId
);
}
// @Override
// public void write(WsResponseModel responseModel, String toAppKey, String toClientId) {
//// WRITE_TASK_THREAD_POOL_EXECUTOR.execute(
//// () -> {
// JsonMapper jsonMapper = new JsonMapper();
// String json = null;
// try {
// json = jsonMapper.writeValueAsString(responseModel);
// } catch (JsonProcessingException e) {
// e.printStackTrace();
// }
// mangerChannelService.writeData(json, toAppKey, toClientId);
// }
// );
//}
@Override
public
void
write
(
WsResponseModel
responseModel
,
String
toAppKey
,
String
toClientId
)
{
JsonMapper
jsonMapper
=
new
JsonMapper
();
String
msgJson
=
null
;
try
{
msgJson
=
jsonMapper
.
writeValueAsString
(
responseModel
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
}
String
msgJson
=
JsonUtils
.
encodeJson
(
responseModel
);
List
<
ClientChannelInfo
>
channelInfos
=
userCacheService
.
getIpByClientIdAndOnline
(
toAppKey
,
toClientId
);
...
...
@@ -130,14 +106,7 @@ public class WriteDataServiceImpl implements WriteDataService {
@Override
public
void
response
(
WsResponseModel
responseModel
,
NioSocketChannel
nioSocketChannel
)
{
JsonMapper
jsonMapper
=
new
JsonMapper
();
String
msgJson
=
null
;
try
{
msgJson
=
jsonMapper
.
writeValueAsString
(
responseModel
);
}
catch
(
JsonProcessingException
e
)
{
e
.
printStackTrace
();
}
String
msgJson
=
JsonUtils
.
encodeJson
(
responseModel
);
// 本地直接下发
nioSocketChannel
.
writeAndFlush
(
new
TextWebSocketFrame
(
msgJson
));
...
...
core/src/main/java/com/wecloud/im/ws/strategy/AbstractImCmdStrategy.java
View file @
60b245ba
package
com
.
wecloud
.
im
.
ws
.
strategy
;
import
com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.wecloud.im.ws.model.request.ReceiveModel
;
import
com.wecloud.im.entity.ImApplication
;
import
com.wecloud.im.entity.ImClient
;
import
com.wecloud.im.service.ImApplicationService
;
import
com.wecloud.im.service.ImClientService
;
import
com.wecloud.im.ws.enums.WsRequestCmdEnum
;
import
com.wecloud.im.ws.model.request.ReceiveVO
;
import
com.wecloud.im.ws.utils.SpringBeanUtils
;
import
com.wecloud.utils.JsonUtils
;
import
io.geekidea.springbootplus.framework.common.exception.BusinessException
;
import
io.netty.channel.ChannelHandlerContext
;
import
lombok.extern.slf4j.Slf4j
;
/**
* @Description 处理Cmd请求
...
...
@@ -11,13 +21,69 @@ import io.netty.channel.ChannelHandlerContext;
* @Author hewei hwei1233@163.com
* @Date 2020-01-02
*/
@Slf4j
public
abstract
class
AbstractImCmdStrategy
{
private
static
ImCmdStrategyFactory
imCmdStrategyFactory
;
private
static
ImApplicationService
imApplicationService
;
private
static
ImClientService
imClientService
;
public
static
void
process
(
String
appKey
,
String
clientId
,
ChannelHandlerContext
ctx
,
String
data
)
throws
JsonProcessingException
{
if
(
log
.
isDebugEnabled
())
{
log
.
debug
(
"appWS收到data: {}\n appKey:{}, clientId:{}, channelId:{}"
,
data
,
appKey
,
clientId
,
ctx
.
channel
().
id
().
asLongText
());
}
if
(
imCmdStrategyFactory
==
null
)
{
synchronized
(
AbstractImCmdStrategy
.
class
)
{
// 双空判断,懒汉模式下的绝对线程安全
if
(
imCmdStrategyFactory
==
null
)
{
imCmdStrategyFactory
=
SpringBeanUtils
.
getBean
(
ImCmdStrategyFactory
.
class
);
imApplicationService
=
SpringBeanUtils
.
getBean
(
ImApplicationService
.
class
);
imClientService
=
SpringBeanUtils
.
getBean
(
ImClientService
.
class
);
}
}
}
// 解析jsonO
ReceiveVO
receiveVO
=
JsonUtils
.
decodeJson
(
data
,
ReceiveVO
.
class
);
if
(
null
==
receiveVO
||
null
==
receiveVO
.
getCmd
())
{
throw
new
BusinessException
(
"null == receiveVO || null == receiveVO.getCmd()"
);
}
WsRequestCmdEnum
wsRequestPathEnum
=
WsRequestCmdEnum
.
getByCode
(
receiveVO
.
getCmd
());
// 使用策略模式, 根据不同类型请求调用不同实现类
AbstractImCmdStrategy
cmdStrategy
=
imCmdStrategyFactory
.
getStrategy
(
wsRequestPathEnum
);
// 查询imApplication
ImApplication
imApplication
=
imApplicationService
.
getOneByAppKey
(
appKey
);
if
(
imApplication
==
null
)
{
log
.
warn
(
"根据appKey: {} 查找不到 imApplication!"
,
appKey
);
return
;
}
// 查询发送者client
ImClient
imClientSender
=
imClientService
.
getOne
(
new
QueryWrapper
<
ImClient
>().
lambda
()
.
eq
(
ImClient:
:
getFkAppid
,
imApplication
.
getId
())
.
eq
(
ImClient:
:
getClientId
,
clientId
));
if
(
imClientSender
==
null
)
{
log
.
warn
(
"根据appKey: {} 查找不到 imClientSender!"
,
imApplication
.
getAppKey
());
return
;
}
cmdStrategy
.
process
(
imApplication
,
imClientSender
,
ctx
,
receiveVO
);
}
/**
* 处理业务流程
*
* @param requestModel
* @param imApplication
* @param imSender
* @param ctx
* @param receiveVO
* @throws Exception
*/
public
abstract
void
process
(
ReceiveModel
requestModel
,
ChannelHandlerContext
ctx
,
String
data
,
String
appKey
,
String
clientId
)
throws
JsonProcessingException
;
public
abstract
void
process
(
ImApplication
imApplication
,
ImClient
imSender
,
ChannelHandlerContext
ctx
,
ReceiveVO
receiveVO
)
;
}
core/src/main/java/com/wecloud/im/ws/strategy/ImCmdStrategyFactory.java
View file @
60b245ba
package
com
.
wecloud
.
im
.
ws
.
strategy
;
import
com.wecloud.im.ws.annotation.ImCmdType
;
import
com.wecloud.im.ws.enums.WsRequestCmdEnum
;
import
com.wecloud.im.ws.utils.ClassScanner
;
import
com.wecloud.im.ws.utils.SpringBeanUtils
;
import
org.springframework.beans.factory.InitializingBean
;
import
org.springframework.boot.context.event.ApplicationStartedEvent
;
import
org.springframework.context.event.EventListener
;
import
org.springframework.stereotype.Component
;
import
org.springframework.util.CollectionUtils
;
import
javax.annotation.PostConstruct
;
import
java.util.HashMap
;
import
java.util.Map
;
import
java.util.Set
;
/**
* @Description 策略模式 上下文
* 维护指令码与策略实现的对应
* @Author hewei hwei1233@163.com
*/
@Component
public
class
ImCmdStrategyFactory
{
private
final
Map
<
WsRequestCmdEnum
,
Class
>
strategyMap
;
public
ImCmdStrategyFactory
(
Map
<
WsRequestCmdEnum
,
Class
>
strategyMap
)
{
this
.
strategyMap
=
strategyMap
;
}
private
final
Map
<
WsRequestCmdEnum
,
AbstractImCmdStrategy
>
strategyMap
=
new
HashMap
<>();
public
AbstractImCmdStrategy
getStrategy
(
WsRequestCmdEnum
wsRequestPathEnum
)
{
...
...
@@ -29,12 +35,19 @@ public class ImCmdStrategyFactory {
throw
new
IllegalArgumentException
(
"strategy map is empty,please check you strategy package path"
);
}
Class
aClass
=
strategyMap
.
get
(
wsRequestPathEnum
);
return
strategyMap
.
get
(
wsRequestPathEnum
);
}
if
(
aClass
==
null
)
{
throw
new
IllegalArgumentException
(
"not fond strategy for type:"
+
wsRequestPathEnum
.
getCmdCode
());
}
@EventListener
(
ApplicationStartedEvent
.
class
)
private
void
init
()
{
// 扫码ReceiveTypeAnnotation注解的类
Set
<
Class
<?>>
classSet
=
ClassScanner
.
scan
(
ImCmdStrategyFactory
.
class
.
getPackage
().
getName
(),
ImCmdType
.
class
);
return
(
AbstractImCmdStrategy
)
SpringBeanUtils
.
getBean
(
aClass
);
classSet
.
forEach
(
clazz
->
{
// 获取注解中的类型值,与枚举类一一对应
WsRequestCmdEnum
type
=
clazz
.
getAnnotation
(
ImCmdType
.
class
).
type
();
strategyMap
.
put
(
type
,
(
AbstractImCmdStrategy
)
SpringBeanUtils
.
getBean
(
clazz
));
});
}
}
core/src/main/java/com/wecloud/im/ws/strategy/ImCmdStrategyProcessor.java
deleted
100644 → 0
View file @
665de18a
package
com
.
wecloud
.
im
.
ws
.
strategy
;
import
com.google.common.collect.Maps
;
import
com.wecloud.im.ws.annotation.ImCmdType
;
import
com.wecloud.im.ws.enums.WsRequestCmdEnum
;
import
com.wecloud.im.ws.utils.ClassScanner
;
import
org.springframework.beans.BeansException
;
import
org.springframework.beans.factory.config.BeanFactoryPostProcessor
;
import
org.springframework.beans.factory.config.ConfigurableListableBeanFactory
;
import
org.springframework.stereotype.Component
;
import
java.util.Map
;
import
java.util.Set
;
/**
* @Description 策略 bean注解扫描注册类
* 扫描自定义注解,将指令码与实现类绑定,将对应关系添加到上下文对象中
* <p>
* BeanStrategyProcessor是spring在容器初始化后对外暴露的扩展点,
* spring ioc容器允许beanFactoryPostProcessor在容器加载注册BeanDefinition后读取BeanDefinition,并能修改它。
* @Author hewei hwei1233@163.com
* @Date 2020-01-02
*/
@Component
public
class
ImCmdStrategyProcessor
implements
BeanFactoryPostProcessor
{
// 扫码注解的包路径
// private static final String STRATEGY_PACK = "com.wecloud.im.ws.strategy.concrete";
@Override
public
void
postProcessBeanFactory
(
ConfigurableListableBeanFactory
configurableListableBeanFactory
)
throws
BeansException
{
Map
<
WsRequestCmdEnum
,
Class
>
handlerMap
=
Maps
.
newHashMapWithExpectedSize
(
5
);
// 扫码ReceiveTypeAnnotation注解的类
Set
<
Class
<?>>
classSet
=
ClassScanner
.
scan
(
ImCmdStrategyProcessor
.
class
.
getPackage
().
getName
(),
ImCmdType
.
class
);
classSet
.
forEach
(
clazz
->
{
// 获取注解中的类型值,与枚举类一一对应
WsRequestCmdEnum
type
=
clazz
.
getAnnotation
(
ImCmdType
.
class
).
type
();
handlerMap
.
put
(
type
,
clazz
);
});
// 初始化Contenxt, 将其注册到spring容器当中
ImCmdStrategyFactory
context
=
new
ImCmdStrategyFactory
(
handlerMap
);
try
{
configurableListableBeanFactory
.
registerResolvableDependency
(
Class
.
forName
(
ImCmdStrategyFactory
.
class
.
getName
()),
context
);
}
catch
(
ClassNotFoundException
e
)
{
e
.
printStackTrace
();
}
}
}
core/src/main/java/com/wecloud/im/ws/strategy/concrete/NormalChatStrategy.java
View file @
60b245ba
This diff is collapsed.
Click to expand it.
core/src/main/java/com/wecloud/im/ws/strategy/concrete/SingleRtcStrategy.java
View file @
60b245ba
//package com.wecloud.im.ws.strategy.concrete;
//
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.json.JsonMapper;
//import com.wecloud.im.service.ImApplicationService;
//import com.wecloud.im.service.ImClientBlacklistService;
//import com.wecloud.im.service.ImClientService;
...
...
@@ -10,7 +9,7 @@
//import com.wecloud.im.service.ImMessageService;
//import com.wecloud.im.ws.annotation.ImCmdType;
//import com.wecloud.im.ws.enums.WsRequestCmdEnum;
//import com.wecloud.im.ws.model.request.Receive
Model
;
//import com.wecloud.im.ws.model.request.Receive
VO
;
//import com.wecloud.im.ws.sender.PushTask;
//import com.wecloud.im.ws.service.WriteDataService;
//import com.wecloud.im.ws.strategy.AbstractImCmdStrategy;
...
...
@@ -28,9 +27,6 @@
//@Slf4j
//public class SingleRtcStrategy extends AbstractImCmdStrategy {
//
//
// private static final JsonMapper JSON_MAPPER = new JsonMapper();
//
// @Autowired
// private ImClientBlacklistService imClientBlacklistService;
//
...
...
@@ -56,7 +52,7 @@
// private PushTask systemPush;
//
// @Override
// public void process(Receive
Model
receiveModel, ChannelHandlerContext ctx, String data, String appKey, String clientId) throws JsonProcessingException {
// public void process(Receive
VO
receiveModel, ChannelHandlerContext ctx, String data, String appKey, String clientId) throws JsonProcessingException {
//
// // 指令判空
// if (receiveModel.getData().get(RtcSubCmd.SUB_CMD) == null) {
...
...
core/src/main/java/com/wecloud/rtc/service/impl/MangerRtcCacheServiceImpl.java
View file @
60b245ba
package
com
.
wecloud
.
rtc
.
service
.
impl
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.json.JsonMapper
;
import
com.wecloud.im.ws.utils.RedisUtils
;
import
com.wecloud.rtc.entity.redis.RtcChannelInfo
;
import
com.wecloud.rtc.entity.redis.RtcRedisKey
;
import
com.wecloud.rtc.service.MangerRtcCacheService
;
import
com.wecloud.utils.JsonUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.stereotype.Service
;
...
...
@@ -47,8 +47,7 @@ public class MangerRtcCacheServiceImpl implements MangerRtcCacheService {
return
null
;
}
JsonMapper
jsonMapper
=
new
JsonMapper
();
return
jsonMapper
.
readValue
(
value
,
RtcChannelInfo
.
class
);
return
JsonUtils
.
decodeJson
(
value
,
RtcChannelInfo
.
class
);
}
...
...
@@ -65,7 +64,7 @@ public class MangerRtcCacheServiceImpl implements MangerRtcCacheService {
//创建时间
rtcChannelInfo
.
setCreateTimestamp
(
System
.
currentTimeMillis
());
String
rtcChannelInfoJson
=
new
JsonMapper
().
writeValueAsString
(
rtcChannelInfo
);
String
rtcChannelInfoJson
=
JsonUtils
.
encodeJson
(
rtcChannelInfo
);
// --- 保存频道信息
String
channelKey
=
String
.
format
(
RtcRedisKey
.
RTC_CHANNEL_INFO
,
rtcChannelId
);
...
...
core/src/main/java/com/wecloud/rtc/service/impl/WsRtcWriteImpl.java
View file @
60b245ba
...
...
@@ -19,7 +19,6 @@ import org.springframework.stereotype.Service;
@Service
public
class
WsRtcWriteImpl
implements
WsRtcWrite
{
// private static final JsonMapper JSON_MAPPER = new JsonMapper();
@Autowired
private
WriteDataService
writeDataService
;
...
...
core/src/main/java/com/wecloud/utils/JsonUtils.java
0 → 100644
View file @
60b245ba
package
com
.
wecloud
.
utils
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.databind.JavaType
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
lombok.extern.slf4j.Slf4j
;
import
org.apache.commons.lang3.StringUtils
;
import
java.io.IOException
;
import
java.util.ArrayList
;
import
java.util.Collections
;
import
java.util.HashMap
;
import
java.util.List
;
/**
* fasterxml 的json工具类
*
* @author lixiaozhong
*/
@Slf4j
public
class
JsonUtils
{
private
static
final
ObjectMapper
OBJECT_MAPPER
=
new
ObjectMapper
();
/**
* Json格式的字符串向JavaBean转换,传入空串将返回null
*
* @param strJsonBody Json格式的字符串
* @param c 目标JavaBean类型
* @return JavaBean对象, 如果解析失败返回 null
*/
public
static
<
T
>
T
decodeJson
(
String
strJsonBody
,
Class
<
T
>
c
)
{
if
(
StringUtils
.
isEmpty
(
strJsonBody
))
{
return
null
;
}
try
{
return
OBJECT_MAPPER
.
readValue
(
strJsonBody
,
c
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"解析json字符串失败,原字符串: {}"
,
strJsonBody
);
return
null
;
}
}
/**
* Json格式的字符串向JavaBean转换,传入空串将返回null (显式抛出异常)
*
* @param strJsonBody Json格式的字符串
* @param c 目标JavaBean类型
* @return JavaBean对象
* @throws IOException
*/
public
static
<
T
>
T
json2Object
(
String
strJsonBody
,
Class
<
T
>
c
)
throws
IOException
{
if
(
StringUtils
.
isEmpty
(
strJsonBody
))
{
return
null
;
}
return
OBJECT_MAPPER
.
readValue
(
strJsonBody
,
c
);
}
/**
* Json格式的字符串向HashMap转换,传入空串将返回空map (显式抛出异常)
*
* @param strJsonBody Json格式的字符串
* @return HashMap对象
* @throws IOException
*/
public
static
HashMap
<
String
,
Object
>
json2Map
(
String
strJsonBody
)
throws
IOException
{
if
(
StringUtils
.
isEmpty
(
strJsonBody
))
{
return
new
HashMap
<
String
,
Object
>();
}
return
OBJECT_MAPPER
.
readValue
(
strJsonBody
,
HashMap
.
class
);
}
/**
* Json格式的字符串向HashMap转换,传入空串将返回空map
*
* @param strJsonBody Json格式的字符串
* @return HashMap对象
* @throws IOException
*/
public
static
HashMap
<
String
,
Object
>
decodeJson2Map
(
String
strJsonBody
)
{
if
(
StringUtils
.
isEmpty
(
strJsonBody
))
{
return
new
HashMap
<
String
,
Object
>();
}
try
{
return
OBJECT_MAPPER
.
readValue
(
strJsonBody
,
HashMap
.
class
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"解析json字符串失败,原字符串: {}"
,
strJsonBody
);
return
null
;
}
}
/**
*将json转换成Object对象
* @param strJsonBody
* @return
* @throws IOException
*/
public
static
Object
json2Object
(
String
strJsonBody
)
throws
IOException
{
if
(
StringUtils
.
isEmpty
(
strJsonBody
))
{
return
null
;
}
// 每个属性的实际类型是string
return
OBJECT_MAPPER
.
readValue
(
strJsonBody
,
Object
.
class
);
}
/**
* Json格式的字符串向JavaBean List集合转换,传入空串将返回空list (显式抛出异常)
*
* @param strJsonBody
* @param c
* @return
* @throws IOException
*/
@SuppressWarnings
(
"unchecked"
)
public
static
<
T
>
List
<
T
>
json2List
(
String
strJsonBody
,
Class
<
T
>
c
)
throws
IOException
{
if
(
StringUtils
.
isEmpty
(
strJsonBody
))
{
return
Collections
.
emptyList
();
}
JavaType
javaType
=
OBJECT_MAPPER
.
getTypeFactory
().
constructParametricType
(
ArrayList
.
class
,
c
);
return
OBJECT_MAPPER
.
readValue
(
strJsonBody
,
javaType
);
}
/**
* Json格式的字符串向JavaBean List集合转换,传入空串将返回空list
*
* @param strJsonBody
* @param c
* @return 对象列表,解析失败返回 null
*/
@SuppressWarnings
(
"unchecked"
)
public
static
<
T
>
List
<
T
>
decodeJsonToList
(
String
strJsonBody
,
Class
<
T
>
c
)
{
if
(
StringUtils
.
isEmpty
(
strJsonBody
))
{
return
Collections
.
emptyList
();
}
JavaType
javaType
=
OBJECT_MAPPER
.
getTypeFactory
().
constructParametricType
(
ArrayList
.
class
,
c
);
try
{
return
OBJECT_MAPPER
.
readValue
(
strJsonBody
,
javaType
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"解析json字符串失败,原字符串: {}"
,
strJsonBody
);
return
null
;
}
}
/**
* Json格式的字符串向List<String>集合转换,传入空串将返回null
*
* @param strJsonBody
* @return
* @throws IOException
*/
public
static
List
<
String
>
json2List
(
String
strJsonBody
)
throws
IOException
{
return
json2List
(
strJsonBody
,
String
.
class
);
}
/**
* Object转为Json格式字符串的方法(显式抛出异常)
*
* @param o
* @return
* @throws JsonProcessingException
*/
public
static
String
object2Json
(
Object
o
)
throws
JsonProcessingException
{
return
OBJECT_MAPPER
.
writeValueAsString
(
o
);
}
/**
* Object转为Json格式字符串的方法
*
* @param o
* @return 对象的json字符串,如果处理过程中出错,返回null
*/
public
static
String
encodeJson
(
Object
o
)
{
try
{
return
OBJECT_MAPPER
.
writeValueAsString
(
o
);
}
catch
(
JsonProcessingException
e
)
{
log
.
warn
(
"对象转换成json失败"
);
return
null
;
}
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment