当前位置:   article > 正文

Java对接腾讯IM即时通话_java实现im通讯

java实现im通讯

一:注册腾讯IM账号

基本配置 - 即时通信 IM - 控制台 (tencent.com)

获得必要的参数:SDKAppIDkey(密钥)

 二:参考管饭API文档进行操作:

即时通信 IM 单发单聊消息-服务端 API-文档中心-腾讯云 (tencent.com)

 三:java中应用:

依赖:

  1. <!-- 腾讯云即时对话pom-->
  2. <dependency>
  3. <groupId>com.github.tencentyun</groupId>
  4. <artifactId>tls-sig-api-v2</artifactId>
  5. <version>2.0</version>
  6. </dependency>

yml配置:

  1. #腾讯云IM即时通话配置
  2. IMConfig:
  3. sdkAppId: 140??????
  4. secretKey: 59c826???你自己的

HttpUtils封装

  1. import com.alibaba.fastjson.JSONObject;
  2. import org.apache.http.Consts;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.NameValuePair;
  6. import org.apache.http.client.HttpClient;
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;
  8. import org.apache.http.client.methods.CloseableHttpResponse;
  9. import org.apache.http.client.methods.HttpGet;
  10. import org.apache.http.client.methods.HttpPost;
  11. import org.apache.http.entity.StringEntity;
  12. import org.apache.http.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.DefaultHttpClient;
  14. import org.apache.http.impl.client.HttpClients;
  15. import org.apache.http.message.BasicNameValuePair;
  16. import org.apache.http.util.EntityUtils;
  17. import java.io.IOException;
  18. import java.util.ArrayList;
  19. import java.util.List;
  20. import java.util.Map;
  21. public class HttpUtil {
  22. private static final CloseableHttpClient httpclient = HttpClients.createDefault();
  23. /**
  24. * 发送HttpGet请求
  25. * @param url
  26. * @return
  27. */
  28. public static String sendGet(String url) {
  29. HttpGet httpget = new HttpGet(url);
  30. CloseableHttpResponse response = null;
  31. try {
  32. response = httpclient.execute(httpget);
  33. } catch (IOException e1) {
  34. e1.printStackTrace();
  35. }
  36. String result = null;
  37. try {
  38. HttpEntity entity = response.getEntity();
  39. if (entity != null) {
  40. result = EntityUtils.toString(entity);
  41. }
  42. } catch (Exception e) {
  43. e.printStackTrace();
  44. } finally {
  45. try {
  46. response.close();
  47. } catch (IOException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. return result;
  52. }
  53. /**
  54. * 发送HttpPost请求,参数为map
  55. * @param url
  56. * @param map
  57. * @return
  58. */
  59. public static String sendPost(String url, Map<String, String> map) {
  60. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  61. for (Map.Entry<String, String> entry : map.entrySet()) {
  62. formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  63. }
  64. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
  65. HttpPost httppost = new HttpPost(url);
  66. httppost.setEntity(entity);
  67. CloseableHttpResponse response = null;
  68. try {
  69. response = httpclient.execute(httppost);
  70. } catch (IOException e) {
  71. e.printStackTrace();
  72. }
  73. HttpEntity entity1 = response.getEntity();
  74. String result = null;
  75. try {
  76. result = EntityUtils.toString(entity1);
  77. } catch (Exception e) {
  78. e.printStackTrace();
  79. }
  80. return result;
  81. }
  82. /**
  83. * 发送不带参数的HttpPost请求
  84. * @param url
  85. * @return
  86. */
  87. public static String sendPost(String url) {
  88. HttpPost httppost = new HttpPost(url);
  89. CloseableHttpResponse response = null;
  90. try {
  91. response = httpclient.execute(httppost);
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. }
  95. HttpEntity entity = response.getEntity();
  96. String result = null;
  97. try {
  98. result = EntityUtils.toString(entity);
  99. } catch (Exception e) {
  100. e.printStackTrace();
  101. }
  102. return result;
  103. }
  104. public static String doPost2(String url, JSONObject param) {
  105. HttpPost httpPost = null;
  106. String result = null;
  107. try {
  108. HttpClient client = new DefaultHttpClient();
  109. httpPost = new HttpPost(url);
  110. if (param != null) {
  111. StringEntity se = new StringEntity(param.toString(), "utf-8");
  112. httpPost.setEntity(se); // post方法中,加入json数据
  113. httpPost.setHeader("Content-Type", "application/json");
  114. httpPost.setHeader("Authorization", param.getString("authorization"));
  115. }
  116. HttpResponse response = client.execute(httpPost);
  117. if (response != null) {
  118. HttpEntity resEntity = response.getEntity();
  119. if (resEntity != null) {
  120. result = EntityUtils.toString(resEntity, "utf-8");
  121. }
  122. }
  123. } catch (Exception ex) {
  124. ex.printStackTrace();
  125. }
  126. return result;
  127. }
  128. }

Redis封装:

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.data.redis.core.*;
  3. import org.springframework.data.redis.support.atomic.RedisAtomicLong;
  4. import org.springframework.stereotype.Component;
  5. import java.io.Serializable;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Set;
  9. import java.util.concurrent.TimeUnit;
  10. @Component
  11. public class RedisServiceUtil {
  12. @Autowired
  13. private RedisTemplate redisTemplate;
  14. /**
  15. * 写入缓存
  16. * @param key
  17. * @param value
  18. * @return
  19. */
  20. public boolean set(final String key, Object value) {
  21. boolean result = false;
  22. try {
  23. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  24. operations.set(key, value);
  25. result = true;
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. return result;
  30. }
  31. /**
  32. * 写入缓存设置时效时间
  33. * @param key
  34. * @param value
  35. * @return
  36. */
  37. public boolean set(final String key, Object value, Long expireTime) {
  38. boolean result = false;
  39. try {
  40. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  41. operations.set(key, value);
  42. redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
  43. result = true;
  44. } catch (Exception e) {
  45. e.printStackTrace();
  46. }
  47. return result;
  48. }
  49. /**
  50. * 设置指定键的过期时间
  51. * @param key 键
  52. * @param expireTime 过期时间
  53. * @param timeUnit 时间单位
  54. * @return true:成功
  55. */
  56. public boolean setExpire(final String key, Long expireTime, TimeUnit timeUnit) {
  57. return redisTemplate.expire(key, expireTime, timeUnit);
  58. }
  59. /**
  60. * 批量删除对应的value
  61. * @param keys
  62. */
  63. public void remove(final String... keys) {
  64. for (String key : keys) {
  65. remove(key);
  66. }
  67. }
  68. /**
  69. * 删除对应的value
  70. * @param key
  71. */
  72. public void remove(final String key) {
  73. if (exists(key)) {
  74. redisTemplate.delete(key);
  75. }
  76. }
  77. /**
  78. * 判断缓存中是否有对应的value
  79. * @param key
  80. * @return
  81. */
  82. public boolean exists(final String key) {
  83. return redisTemplate.hasKey(key);
  84. }
  85. /**
  86. * 读取缓存
  87. * @param key
  88. * @return
  89. */
  90. public <T> T get(final String key) {
  91. Object result = null;
  92. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  93. result = operations.get(key);
  94. if (null == result) {
  95. return null;
  96. }
  97. return (T)result;
  98. }
  99. /**
  100. * 哈希 添加
  101. * @param key
  102. * @param hashKey
  103. * @param value
  104. */
  105. public void hmSet(String key, Object hashKey, Object value) {
  106. HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
  107. hash.put(key,hashKey,value);
  108. }
  109. /**
  110. * 以map集合的形式添加键值对
  111. * @param key 键
  112. * @param map Map
  113. */
  114. public void hPutAll(String key, Map<String, Object> map) {
  115. redisTemplate.opsForHash().putAll(key, map);
  116. }
  117. /**
  118. * 哈希获取数据
  119. * @param key
  120. * @param hashKey
  121. * @return
  122. */
  123. public Object hmGet(String key, Object hashKey) {
  124. HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
  125. return hash.get(key,hashKey);
  126. }
  127. /**
  128. * 根据键获取到redis中存储的map
  129. * @param key 键
  130. * @return 键对应的map
  131. */
  132. public Map<String, Object> hGetAll(String key) {
  133. return redisTemplate.opsForHash().entries(key);
  134. }
  135. /**
  136. * 自增/自减key对应map中的指定字段的long型数值
  137. * @param key 键
  138. * @param field key对应map中存储的字段
  139. * @param increment 正数-自增;负数-自减
  140. * @return 自增/自减后的数值
  141. */
  142. public Long hashIncrBy(String key, Object field, long increment) {
  143. return redisTemplate.opsForHash().increment(key, field, increment);
  144. }
  145. /**
  146. * 自增/自减key对应map中的指定字段的double型数值
  147. * @param key 键
  148. * @param field key对应map中存储的字段
  149. * @param delta 正数-自增;负数-自减
  150. * @return 自增/自减后的数值
  151. */
  152. public Double hIncrByDouble(String key, Object field, double delta) {
  153. return redisTemplate.opsForHash().increment(key, field, delta);
  154. }
  155. /**
  156. * 查询redis中指定字段是否存在
  157. * @param key 键
  158. * @param field key对应map中存储的字段
  159. * @return true:存在
  160. */
  161. public boolean hashExists(String key, String field) {
  162. return redisTemplate.opsForHash().hasKey(key, field);
  163. }
  164. /**
  165. * 列表添加
  166. * @param k
  167. * @param v
  168. */
  169. public void lPush(String k, Object v) {
  170. ListOperations<String, Object> list = redisTemplate.opsForList();
  171. list.rightPush(k,v);
  172. }
  173. /**
  174. * 列表获取
  175. * @param k
  176. * @param l
  177. * @param l1
  178. * @return
  179. */
  180. public List<Object> lRange(String k, long l, long l1) {
  181. ListOperations<String, Object> list = redisTemplate.opsForList();
  182. return list.range(k,l,l1);
  183. }
  184. /**
  185. * 集合添加
  186. * @param key
  187. * @param value
  188. */
  189. public void add(String key, Object value) {
  190. SetOperations<String, Object> set = redisTemplate.opsForSet();
  191. set.add(key,value);
  192. }
  193. /**
  194. * 集合获取
  195. * @param key
  196. * @return
  197. */
  198. public Set<Object> setMembers(String key) {
  199. SetOperations<String, Object> set = redisTemplate.opsForSet();
  200. return set.members(key);
  201. }
  202. /**
  203. * 有序集合添加
  204. * @param key
  205. * @param value
  206. * @param scoure
  207. */
  208. public void zAdd(String key, Object value, double scoure) {
  209. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  210. zset.add(key,value,scoure);
  211. }
  212. /**
  213. * 有序集合获取
  214. * @param key
  215. * @param scoure
  216. * @param scoure1
  217. * @return
  218. */
  219. public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
  220. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  221. return zset.rangeByScore(key, scoure, scoure1);
  222. }
  223. /**
  224. * redis原子型自增
  225. * */
  226. public Long incr(String key){
  227. RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
  228. Long increment = entityIdCounter.getAndIncrement();
  229. return increment;
  230. }
  231. }

Api接口封装:

  1. package com.furnish.web.wn.enums.txim;
  2. /**
  3. * @description: 腾讯im相关API接口
  4. */
  5. public class TencentCloudImApiConstant {
  6. /**
  7. * 账号管理
  8. */
  9. public static class AccountManage {
  10. /**导入单个帐号*/
  11. public static final String ACCOUNT_IMPORT = "v4/im_open_login_svc/account_import";
  12. /**导入多个帐号*/
  13. public static final String MULTI_ACCOUNT_IMPORT = "v4/im_open_login_svc/account_import";
  14. /**删除帐号*/
  15. public static final String ACCOUNT_DELETE = "v4/im_open_login_svc/account_delete";
  16. /**查询帐号*/
  17. public static final String ACCOUNT_CHECK = "v4/im_open_login_svc/account_check";
  18. /**失效帐号登录状态*/
  19. public static final String ACCOUNT_KICK = "v4/im_open_login_svc/kick";
  20. /**查询账号在线状态*/
  21. public static final String ACCOUNT_QUERY_STATE = "v4/openim/querystate";
  22. }
  23. /**
  24. * 单聊消息
  25. */
  26. public static class SingleChatManage {
  27. /**单发单聊消息*/
  28. public static final String SEND_MSG = "v4/openim/sendmsg";
  29. /**批量发单聊消息*/
  30. public static final String BATCH_SEND_MSG = "v4/openim/batchsendmsg";
  31. /**导入单聊消息*/
  32. public static final String IMPORT_MSG = "v4/openim/importmsg";
  33. /**查询单聊消息*/
  34. public static final String ADMIN_GET_ROAM_MSG = "v4/openim/admin_getroammsg";
  35. /**撤回单聊消息*/
  36. public static final String ADMIN_MSG_WITH_DRAW = "v4/openim/admin_msgwithdraw";
  37. /**设置单聊消息已读*/
  38. public static final String ADMIN_SET_MSG_READ = "v4/openim/admin_set_msg_read";
  39. }
  40. /**
  41. * 全员推送
  42. */
  43. public static class AllPushManage {
  44. /**全员推送*/
  45. public static final String IM_PUSH = "v4/all_member_push/im_push";
  46. /**设置应用属性名称*/
  47. public static final String IM_SET_ATTR_NAME = "v4/all_member_push/im_set_attr_name";
  48. /**获取应用属性名称*/
  49. public static final String IM_GET_ATTR_NAME = "v4/all_member_push/im_get_attr_name";
  50. /**获取用户属性*/
  51. public static final String IM_GET_ATTR = "v4/all_member_push/im_get_attr";
  52. /**设置用户属性*/
  53. public static final String IM_SET_ATTR = "v4/all_member_push/im_set_attr";
  54. /**删除用户属性*/
  55. public static final String IM_REMOVE_ATTR = "v4/all_member_push/im_remove_attr";
  56. /**获取用户标签*/
  57. public static final String IM_GET_TAG = "v4/all_member_push/im_get_tag";
  58. /**添加用户标签*/
  59. public static final String IM_ADD_TAG = "v4/all_member_push/im_add_tag";
  60. /**删除用户标签*/
  61. public static final String IM_REMOVE_TAG = "v4/all_member_push/im_remove_tag";
  62. /**删除用户所有标签*/
  63. public static final String IM_REMOVE_ALL_TAGS = "v4/all_member_push/im_remove_all_tags";
  64. }
  65. /**
  66. * 资料管理
  67. */
  68. public static class PortraitManage {
  69. /**设置资料*/
  70. public static final String PORTRAIT_SET = "v4/profile/portrait_set";
  71. /**拉取资料*/
  72. public static final String PORTRAIT_GET = "v4/profile/portrait_get";
  73. }
  74. /**
  75. * 关系链管理
  76. */
  77. public static class RelationManage {
  78. /**添加好友*/
  79. public static final String FRIEND_ADD = "v4/sns/friend_add";
  80. /**导入好友*/
  81. public static final String FRIEND_IMPORT = "v4/sns/friend_import";
  82. /**更新好友*/
  83. public static final String FRIEND_UPDATE = "v4/sns/friend_update";
  84. /**删除好友*/
  85. public static final String FRIEND_DELETE = "v4/sns/friend_delete";
  86. /**删除所有好友*/
  87. public static final String FRIEND_DELETE_ALL = "v4/sns/friend_delete_all";
  88. /**校验好友*/
  89. public static final String FRIEND_CHECK = "v4/sns/friend_check";
  90. /**拉取好友*/
  91. public static final String FRIEND_GET = "v4/sns/friend_get";
  92. /**拉取指定好友*/
  93. public static final String FRIEND_GET_LIST = "v4/sns/friend_get_list";
  94. /**添加黑名单*/
  95. public static final String BLACK_LIST_ADD = "v4/sns/black_list_add";
  96. /**删除黑名单*/
  97. public static final String BLACK_LIST_DELETE = "v4/sns/black_list_delete";
  98. /**拉取黑名单*/
  99. public static final String BLACK_LIST_GET = "v4/sns/black_list_get";
  100. /**校验黑名单*/
  101. public static final String BLACK_LIST_CHECK = "v4/sns/black_list_check";
  102. /**添加分组*/
  103. public static final String GROUP_ADD = "v4/sns/group_add";
  104. /**删除分组*/
  105. public static final String GROUP_DELETE = "v4/sns/group_delete";
  106. /**拉取分组*/
  107. public static final String GROUP_GET = "v4/sns/group_get";
  108. }
  109. /**
  110. * 群组管理
  111. */
  112. public static class GroupManage {
  113. /**创建群组*/
  114. public static final String CREATE_GROUP = "v4/group_open_http_svc/create_group";
  115. /**获取群详细资料*/
  116. public static final String GET_GROUP_INFO = "v4/group_open_http_svc/get_group_info";
  117. /**获取群成员详细资料*/
  118. public static final String GET_GROUP_MEMBER_INFO = "v4/group_open_http_svc/get_group_member_info";
  119. /**修改群基础资料*/
  120. public static final String MODIFY_GROUP_BASE_INFO = "v4/group_open_http_svc/modify_group_base_info";
  121. /**增加群成员*/
  122. public static final String ADD_GROUP_MEMBER = "v4/group_open_http_svc/add_group_member";
  123. /**删除群成员*/
  124. public static final String DELETE_GROUP_MEMBER = "v4/group_open_http_svc/delete_group_member";
  125. /**修改群成员资料*/
  126. public static final String MODIFY_GROUP_MEMBER_INFO = "v4/group_open_http_svc/modify_group_member_info";
  127. /**解散群组*/
  128. public static final String DESTROY_GROUP = "v4/group_open_http_svc/destroy_group";
  129. /**获取用户所加入的群组*/
  130. public static final String GET_JOINED_GROUP_LIST = "v4/group_open_http_svc/get_joined_group_list";
  131. /**查询用户在群组中的身份*/
  132. public static final String GET_ROLE_IN_GROUP = "v4/group_open_http_svc/get_role_in_group";
  133. /**批量禁言和取消禁言*/
  134. public static final String FORBID_SEND_MSG = "v4/group_open_http_svc/forbid_send_msg";
  135. /**获取被禁言群成员列表*/
  136. public static final String GET_GROUP_SHUT_UIN = "v4/group_open_http_svc/get_group_shutted_uin";
  137. /**在群组中发送普通消息*/
  138. public static final String SEND_GROUP_MSG = "v4/group_open_http_svc/send_group_msg";
  139. /**在群组中发送系统通知*/
  140. public static final String SEND_GROUP_SYSTEM_NOTIFICATION = "v4/group_open_http_svc/send_group_system_notification";
  141. /**撤回群消息*/
  142. public static final String GROUP_MSG_RECALL = "v4/group_open_http_svc/group_msg_recall";
  143. /**转让群主*/
  144. public static final String CHANGE_GROUP_OWNER = "v4/group_open_http_svc/change_group_owner";
  145. /**导入群基础资料*/
  146. public static final String IMPORT_GROUP = "v4/group_open_http_svc/import_group";
  147. /**导入群消息*/
  148. public static final String IMPORT_GROUP_MSG = "v4/group_open_http_svc/import_group_msg";
  149. /**导入群成员*/
  150. public static final String IMPORT_GROUP_MEMBER = "v4/group_open_http_svc/import_group_member";
  151. /**设置成员未读消息计数*/
  152. public static final String SET_UNREAD_MSG_NUM = "v4/group_open_http_svc/set_unread_msg_num";
  153. /**删除指定用户发送的消息*/
  154. public static final String DELETE_GROUP_MSG_BY_SENDER = "v4/group_open_http_svc/delete_group_msg_by_sender";
  155. /**拉取群历史消息*/
  156. public static final String GROUP_MSG_GET_SIMPLE = "v4/group_open_http_svc/group_msg_get_simple";
  157. /**获取直播群在线人数*/
  158. public static final String GET_ONLINE_MEMBER_NUM = "v4/group_open_http_svc/get_online_member_num";
  159. }
  160. /**
  161. * 全局禁言管理
  162. */
  163. public static class AllSinentManage {
  164. /**设置全局禁言*/
  165. public static final String SET_NO_SPEAKING = "v4/openconfigsvr/setnospeaking";
  166. /**查询全局禁言*/
  167. public static final String GET_NO_SPEAKING = "v4/openconfigsvr/getnospeaking";
  168. }
  169. /**
  170. * 运营管理
  171. */
  172. public static class OperationManage {
  173. /**拉取运营数据*/
  174. public static final String GET_APP_INFO = "v4/openconfigsvr/getappinfo";
  175. /**下载消息记录*/
  176. public static final String GET_HISTORY = "v4/open_msg_svc/get_history";
  177. /**获取服务器 IP 地址*/
  178. public static final String GET_IP_LIST = "v4/ConfigSvc/GetIPList";
  179. }
  180. }

腾讯Im相关常量:

  1. /**
  2. * @description: 腾讯im相关常量
  3. */
  4. public class TencentCloudImConstant {
  5. /**
  6. * IM请求处理结果
  7. */
  8. public final static String ACTION_STATUS_OK = "OK";
  9. public final static String ACTION_STATUS_FAIL = "FAIL";
  10. /**
  11. * IM发消息是否同步到发送方(1-同步,2-不同步)
  12. */
  13. public final static Integer SYNC_OTHER_MACHINE_YES = 1;
  14. public final static Integer SYNC_OTHER_MACHINE_NO = 2;
  15. /**
  16. * IM消息对象类型:
  17. * TIMTextElem 文本消息。
  18. * TIMLocationElem 地理位置消息。
  19. * TIMFaceElem 表情消息。
  20. * TIMCustomElem 自定义消息,当接收方为 iOS 系统且应用处在后台时,此消息类型可携带除文本以外的字段到 APNs。一条组合消息中只能包含一个 TIMCustomElem 自定义消息元素。
  21. * TIMSoundElem 语音消息。
  22. * TIMImageElem 图像消息。
  23. * TIMFileElem 文件消息。
  24. * TIMVideoFileElem 视频消息。
  25. */
  26. public final static String TIM_TEXT_ELEM = "TIMTextElem";
  27. public final static String TIM_LOCATION_ELEM = "TIMLocationElem";
  28. public final static String TIM_FACE_ELEM = "TIMFaceElem";
  29. public final static String TIM_CUSTOM_ELEM = "TIMCustomElem";
  30. public final static String TIM_SOUND_ELEM = "TIMSoundElem";
  31. public final static String TIM_IMAGE_ELEM = "TIMImageElem";
  32. public final static String TIM_FILE_ELEM = "TIMFileElem";
  33. public final static String TIM_VIDEOFILE_ELEM = "TIMVideoFileElem";
  34. /**
  35. * 微信响应消息类型
  36. * WX_MSG_TYPE_EVENT:事件类型,事件类型对应"user_enter_tempsession"表示建立会话
  37. * WX_MSG_TYPE_TEXT:文本类型
  38. * WX_MSG_TYPE_TEXT:图片类型
  39. * WX_MSG_TYPE_TEXT:小程序卡片
  40. */
  41. public final static String WX_MSG_TYPE_EVENT = "event";
  42. public final static String WX_MSG_TYPE_TEXT = "text";
  43. public final static String WX_MSG_TYPE_IMAGE = "image";
  44. public final static String WX_MSG_TYPE_APPLET_CARD = "miniprogrampage";
  45. }

功能配置:

  1. import com.alibaba.fastjson.JSONObject;
  2. import com.tencentyun.TLSSigAPIv2;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.apache.commons.lang3.RandomUtils;
  5. import org.apache.commons.lang3.StringUtils;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.beans.factory.annotation.Value;
  8. import org.springframework.stereotype.Component;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.stream.Collectors;
  12. /**
  13. * @description: 腾讯im基础配置
  14. * @author: zyb
  15. * @date: 2021/5/27 17:32
  16. */
  17. @Slf4j
  18. @Component
  19. public class TencentCloudImUtil {
  20. private static final String HTTPS_URL_PREFIX = "https://console.tim.qq.com/";
  21. private static final String APP_MANAGER = "administrator";
  22. private static final String REDIS_IM_USER_SIG = "silence:im_user_sig:";
  23. @Value("${IMConfig.sdkAppId}")
  24. private long sdkAppId;
  25. @Value("${IMConfig.secretKey}")
  26. private String secretKey;
  27. @Autowired
  28. private RedisServiceUtil redisServiceUtil;
  29. /**
  30. * 获取腾讯云用户签名
  31. */
  32. public String getTxCloudUserSig() {
  33. String userSig = redisServiceUtil.get(REDIS_IM_USER_SIG + APP_MANAGER);
  34. if (StringUtils.isEmpty(userSig)) {
  35. TLSSigAPIv2 tlsSigApi = new TLSSigAPIv2(sdkAppId, secretKey);
  36. userSig = tlsSigApi.genUserSig(APP_MANAGER, 86400);
  37. redisServiceUtil.set(REDIS_IM_USER_SIG + APP_MANAGER, userSig, 86400L);
  38. }
  39. return userSig;
  40. }
  41. /**
  42. * 获取腾讯im请求路径
  43. */
  44. private String getHttpsUrl(String imServiceApi, Integer random) {
  45. return String.format("%s%s?sdkappid=%s&identifier=%s&usersig=%s&random=%s&contenttype=json",
  46. HTTPS_URL_PREFIX, imServiceApi, sdkAppId, APP_MANAGER, this.getTxCloudUserSig(), random);
  47. }
  48. /**
  49. * 导入单个账号
  50. * @param userId 用户id
  51. */
  52. public void accountImport(String userId) {
  53. accountImport(userId, null);
  54. }
  55. public void accountImport(String userId, String userName) {
  56. accountImport(userId, userName, null);
  57. }
  58. public void accountImport(String userId, String userName, String faceUrl) {
  59. Integer random = RandomUtils.nextInt(0, 999999999);
  60. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_IMPORT, random);
  61. JSONObject jsonObject = new JSONObject();
  62. jsonObject.put("Identifier", userId);
  63. if (StringUtils.isNotEmpty(userName)) {
  64. jsonObject.put("Nick", userName);
  65. }
  66. if (StringUtils.isNotEmpty(faceUrl)) {
  67. jsonObject.put("FaceUrl", faceUrl);
  68. }
  69. log.info("腾讯云im导入单个账号,请求参数:{}", jsonObject.toString());
  70. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  71. log.info("腾讯云im导入单个账号,返回结果:{}", result);
  72. }
  73. /**
  74. * 导入多个账号
  75. * @param userIds 用户id集合
  76. */
  77. public void multiAccountImport(List<String> userIds) {
  78. Integer random = RandomUtils.nextInt(0, 999999999);
  79. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.MULTI_ACCOUNT_IMPORT, random);
  80. JSONObject jsonObject = new JSONObject();
  81. jsonObject.put("Accounts", userIds);
  82. log.info("腾讯云im导入多个账号,请求参数:{}", jsonObject.toString());
  83. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  84. log.info("腾讯云im导入单个账户,返回结果:{}", result);
  85. }
  86. /**
  87. * 删除账号
  88. * @param userIds 用户id集合
  89. */
  90. public void accountDelete(List<String> userIds) {
  91. Integer random = RandomUtils.nextInt(0, 999999999);
  92. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_DELETE, random);
  93. JSONObject jsonObject = new JSONObject();
  94. jsonObject.put("DeleteItem", getUserIdJsonList(userIds));
  95. log.info("腾讯云im删除账号,请求参数:{}", jsonObject.toString());
  96. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  97. log.info("腾讯云im删除账户,返回结果:{}", result);
  98. }
  99. /**
  100. * 查询账号是否已经导入im
  101. * @param userIds 用户id集合
  102. */
  103. public String accountCheck(List<String> userIds) {
  104. Integer random = RandomUtils.nextInt(0, 999999999);
  105. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.AccountManage.ACCOUNT_CHECK, random);
  106. JSONObject jsonObject = new JSONObject();
  107. jsonObject.put("CheckItem", getUserIdJsonList(userIds));
  108. log.info("腾讯云im查询账号,请求参数:{}", jsonObject.toString());
  109. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  110. log.info("腾讯云im查询账号,返回结果:{}", result);
  111. return result;
  112. }
  113. private List<JSONObject> getUserIdJsonList(List<String> userIds) {
  114. return userIds.stream().map(v -> {
  115. JSONObject userIdJson = new JSONObject();
  116. userIdJson.put("UserID", v);
  117. return userIdJson;
  118. }).collect(Collectors.toList());
  119. }
  120. /**
  121. * 单发单聊消息
  122. * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
  123. * @param fromUserId 发送方用户id
  124. * @param toUserId 接收方用户id
  125. * @param msgType 消息对象类型
  126. * @param msgContent 消息内容
  127. */
  128. public String sendMsg(Integer syncOtherMachine, String fromUserId, String toUserId, String msgType, String msgContent) {
  129. Integer random = RandomUtils.nextInt(0, 999999999);
  130. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.SEND_MSG, random);
  131. JSONObject jsonObject = new JSONObject();
  132. jsonObject.put("SyncOtherMachine", syncOtherMachine);
  133. if (StringUtils.isNotEmpty(fromUserId)) {
  134. // 发送方不为空表示指定发送用户,为空表示为管理员发送消息
  135. jsonObject.put("From_Account", fromUserId);
  136. }
  137. jsonObject.put("To_Account", toUserId);
  138. jsonObject.put("MsgRandom", random);
  139. List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
  140. jsonObject.put("MsgBody", msgBody);
  141. log.info("腾讯云im单发单聊消息,请求参数:{}", jsonObject.toString());
  142. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  143. log.info("腾讯云im单发单聊消息,返回结果:{}", result);
  144. return result;
  145. }
  146. /**
  147. * 批量发单聊消息
  148. * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
  149. * @param fromUserId 发送方用户id
  150. * @param toUserIds 接收方用户id集合
  151. * @param msgType 消息对象类型
  152. * @param msgContent 消息内容
  153. */
  154. public String batchSendMsg(Integer syncOtherMachine, String fromUserId, List<String> toUserIds, String msgType, String msgContent) {
  155. Integer random = RandomUtils.nextInt(0, 999999999);
  156. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.BATCH_SEND_MSG, random);
  157. JSONObject jsonObject = new JSONObject();
  158. jsonObject.put("SyncOtherMachine", syncOtherMachine);
  159. if (StringUtils.isNotEmpty(fromUserId)) {
  160. // 发送方不为空表示指定发送用户,为空表示为管理员发送消息
  161. jsonObject.put("From_Account", fromUserId);
  162. }
  163. jsonObject.put("To_Account", toUserIds);
  164. jsonObject.put("MsgRandom", random);
  165. List<JSONObject> msgBody = getMsgBody(msgType, msgContent);
  166. jsonObject.put("MsgBody", msgBody);
  167. log.info("腾讯云im批量发单聊消息,请求参数:{}", jsonObject.toString());
  168. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  169. log.info("腾讯云im批量发单聊消息,返回结果:{}", result);
  170. return result;
  171. }
  172. /**
  173. * 拼接发送消息内容
  174. * @param msgType 消息类型
  175. * @param msgContent 发送消息内容
  176. * @return 消息内容
  177. */
  178. private List<JSONObject> getMsgBody(String msgType, String msgContent) {
  179. List<JSONObject> msgBody = new ArrayList<>();
  180. if (msgType.equals(TencentCloudImConstant.TIM_TEXT_ELEM)) {
  181. // 文本类型
  182. JSONObject msgBodyJson = new JSONObject();
  183. msgBodyJson.put("MsgType", msgType);
  184. JSONObject msgContentObj = new JSONObject();
  185. msgContentObj.put("Text", msgContent);
  186. msgBodyJson.put("MsgContent", msgContentObj);
  187. msgBody.add(msgBodyJson);
  188. }
  189. return msgBody;
  190. }
  191. /**
  192. * 查询单聊消息
  193. * @param fromUserId 发送方用户id
  194. * @param toUserId 接收方用户id
  195. * @param maxCnt 查询条数
  196. * @param startTime 起始时间(单位:秒)
  197. * @param endTime 结束时间(单位:秒)
  198. * @param lastMsgKey 最后一条消息的 MsgKey
  199. * @return 单聊消息列表
  200. */
  201. public String adminGetRoamMsg(String fromUserId, String toUserId, Integer maxCnt, Long startTime, Long endTime, String lastMsgKey) {
  202. Integer random = RandomUtils.nextInt(0, 999999999);
  203. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_GET_ROAM_MSG, random);
  204. JSONObject jsonObject = new JSONObject();
  205. jsonObject.put("From_Account", fromUserId);
  206. jsonObject.put("To_Account", toUserId);
  207. jsonObject.put("MaxCnt", maxCnt);
  208. jsonObject.put("MinTime", startTime);
  209. jsonObject.put("MaxTime", endTime);
  210. if (StringUtils.isNotEmpty(lastMsgKey)){
  211. jsonObject.put("LastMsgKey", lastMsgKey);
  212. }
  213. log.info("腾讯云im查询单聊消息,请求参数:{}", jsonObject.toString());
  214. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  215. log.info("腾讯云im查询单聊消息,返回结果:{}", result);
  216. return result;
  217. }
  218. /**
  219. * 撤回单聊消息
  220. * @param fromUserId 发送方用户id
  221. * @param toUserId 接收方用户id
  222. * @param msgKey MsgKey
  223. */
  224. public void adminMsgWithDraw(String fromUserId, String toUserId, String msgKey) {
  225. Integer random = RandomUtils.nextInt(0, 999999999);
  226. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_MSG_WITH_DRAW, random);
  227. JSONObject jsonObject = new JSONObject();
  228. jsonObject.put("From_Account", fromUserId);
  229. jsonObject.put("To_Account", toUserId);
  230. jsonObject.put("MsgKey", msgKey);
  231. log.info("腾讯云im撤回单聊消息,请求参数:{}", jsonObject.toString());
  232. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  233. log.info("腾讯云im撤回单聊消息,返回结果:{}", result);
  234. }
  235. /**
  236. * 设置单聊消息已读
  237. * @param reportUserId 读取消息的用户
  238. * @param peerUserId 发送消息的用户
  239. */
  240. public void adminSetMsgRead(String reportUserId, String peerUserId) {
  241. Integer random = RandomUtils.nextInt(0, 999999999);
  242. String httpsUrl = getHttpsUrl(TencentCloudImApiConstant.SingleChatManage.ADMIN_SET_MSG_READ, random);
  243. JSONObject jsonObject = new JSONObject();
  244. jsonObject.put("Report_Account", reportUserId);
  245. jsonObject.put("Peer_Account", peerUserId);
  246. log.info("腾讯云im设置单聊消息已读,请求参数:{}", jsonObject.toString());
  247. String result = HttpUtil.doPost2(httpsUrl, jsonObject);
  248. log.info("腾讯云im设置单聊消息已读,返回结果:{}", result);
  249. }
  250. }

接口调用:

  1. import com.furnish.web.wn.enums.txim.TencentCloudImUtil;
  2. import io.swagger.annotations.Api;
  3. import io.swagger.annotations.ApiImplicitParam;
  4. import io.swagger.annotations.ApiImplicitParams;
  5. import io.swagger.annotations.ApiOperation;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import java.util.*;
  11. @RestController
  12. @RequestMapping("/wnapp")
  13. @Api(tags = "腾讯IM实时对话")
  14. public class TXController {
  15. @Autowired
  16. private TencentCloudImUtil tencentCloudImUtil;
  17. @GetMapping("/contextLoads")
  18. @ApiOperation("获取userSig")
  19. public String contextLoads() {
  20. String userSig = tencentCloudImUtil.getTxCloudUserSig();
  21. System.out.println(userSig);
  22. return userSig;
  23. }
  24. /**
  25. * 查询单聊消息
  26. * @param fromUserId 发送方用户id
  27. * @param toUserId 接收方用户id
  28. * @param maxCnt 查询条数
  29. * @param startTime 起始时间(单位:秒)
  30. * @param endTime 结束时间(单位:秒)
  31. * @param lastMsgKey 最后一条消息的 MsgKey 可以为null
  32. * @return 单聊消息列表
  33. */
  34. @GetMapping("/testSendIMMsg")
  35. @ApiOperation("查询单聊消息")
  36. @ApiImplicitParams({
  37. @ApiImplicitParam(name = "fromUserId", value = "发送方用户id", dataType = "String", dataTypeClass = Integer.class),
  38. @ApiImplicitParam(name = "toUserId", value = "接收方用户id", dataType = "String", dataTypeClass = String.class),
  39. @ApiImplicitParam(name = "maxCnt", value = "查询条数", dataType = "Integer", dataTypeClass = Integer.class),
  40. @ApiImplicitParam(name = "startTime", value = "起始时间(单位:秒)", dataType = "Long", dataTypeClass = Long.class),
  41. @ApiImplicitParam(name = "endTime", value = "结束时间(单位:秒)", dataType = "Long", dataTypeClass = Long.class),
  42. @ApiImplicitParam(name = "lastMsgKey", value = "最后一条消息的 MsgKey 可以为null", dataType = "String", dataTypeClass = String.class)
  43. })
  44. public String testSendIMMsg(String fromUserId,String toUserId,Integer maxCnt,Long startTime,Long endTime,String lastMsgKey){
  45. Calendar cale = Calendar.getInstance();
  46. cale.setTime(new Date());
  47. cale.set(Calendar.HOUR_OF_DAY, 0);
  48. cale.set(Calendar.MINUTE, 0);
  49. cale.set(Calendar.SECOND, 0);
  50. // Date beginTime = cale.getTime();
  51. String s = tencentCloudImUtil.adminGetRoamMsg(fromUserId, toUserId, maxCnt, startTime, endTime, lastMsgKey);
  52. return s;
  53. }
  54. /**
  55. * 查询账号是否已经导入im
  56. * @param userIds 用户id集合
  57. */
  58. @GetMapping("/testAccount")
  59. @ApiOperation("查询账号是否已经导入im")
  60. @ApiImplicitParam(name = "userIds",value = "用户id集合")
  61. public String testAccount(List<String> userIds){
  62. String accountCheck = tencentCloudImUtil.accountCheck(userIds);
  63. System.out.println(accountCheck);
  64. return accountCheck;
  65. }
  66. /**
  67. * 单发单聊消息
  68. * @param syncOtherMachine 是否同步消息到发送方(1-同步,2-不同步)
  69. * @param fromUserId 发送方用户id
  70. * @param toUserId 接收方用户id
  71. * @param msgType 消息对象类型
  72. * @param msgContent 消息内容
  73. */
  74. @GetMapping("/sendMsg")
  75. @ApiOperation("单发单聊消息")
  76. @ApiImplicitParams({
  77. @ApiImplicitParam(name = "syncOtherMachine", value = "是否同步消息到发送方(1-同步,2-不同步)", dataType = "Integer", dataTypeClass = Integer.class),
  78. @ApiImplicitParam(name = "fromUserId", value = "发送方用户id", dataType = "String", dataTypeClass = String.class),
  79. @ApiImplicitParam(name = "toUserId", value = "接收方用户id", dataType = "String", dataTypeClass = String.class),
  80. @ApiImplicitParam(name = "msgType", value = "消息对象类型", dataType = "String", dataTypeClass = String.class),
  81. @ApiImplicitParam(name = "msgContent", value = "消息内容", dataType = "String", dataTypeClass = String.class)
  82. })
  83. public String sendMsg(Integer syncOtherMachine,String fromUserId,String toUserId,String msgType,String msgContent){
  84. String sendMsg = tencentCloudImUtil.sendMsg(syncOtherMachine,fromUserId,toUserId,msgType,msgContent);
  85. System.out.println(sendMsg);
  86. return sendMsg;
  87. }
  88. /**
  89. * 撤回单聊消息
  90. * 发送方用户id
  91. * 接收方用户id
  92. * MsgKey
  93. */
  94. @GetMapping("/adminMsgWithDraw")
  95. @ApiOperation("撤回单聊消息")
  96. @ApiImplicitParams({
  97. @ApiImplicitParam(name = "fromUserId", value = "发送方用户id", dataType = "String", dataTypeClass = String.class),
  98. @ApiImplicitParam(name = "toUserId", value = "接收方用户id", dataType = "String", dataTypeClass = String.class),
  99. @ApiImplicitParam(name = "msgKey", value = "当前信息key", dataType = "String", dataTypeClass = String.class)
  100. })
  101. public void adminMsgWithDraw(String fromUserId,String toUserId,String msgKey){
  102. tencentCloudImUtil.adminMsgWithDraw(fromUserId, toUserId, msgKey);
  103. }
  104. /**
  105. * 设置单聊消息已读
  106. * @param reportUserId 读取消息的用户
  107. * @param peerUserId 发送消息的用户
  108. */
  109. @GetMapping("/adminSetMsgRead")
  110. @ApiOperation("设置单聊消息已读")
  111. @ApiImplicitParams({
  112. @ApiImplicitParam(name = "reportUserId", value = "读取消息的用户", dataType = "String", dataTypeClass = String.class),
  113. @ApiImplicitParam(name = "peerUserId", value = "发送消息的用户", dataType = "String", dataTypeClass = String.class)
  114. })
  115. public void adminSetMsgRead(String reportUserId,String peerUserId){
  116. tencentCloudImUtil.adminSetMsgRead(reportUserId,peerUserId);
  117. }
  118. /**
  119. * 删除账号
  120. * @param userIds 账号集合
  121. */
  122. @GetMapping("/accountDelete")
  123. @ApiOperation("删除账号")
  124. @ApiImplicitParam(name = "userIds",value = "账号集合")
  125. public void accountDelete(List<String> userIds){
  126. tencentCloudImUtil.accountDelete(userIds);
  127. }
  128. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/178596
推荐阅读
相关标签
  

闽ICP备14008679号