即时通信服务
作者:互联网
1.本案采用了环信提供的即时通信服务,并封装成spring的自动装配类
public class HuanXinTemplate { private EMService service; public HuanXinTemplate(HuanXinProperties properties) { EMProperties emProperties = EMProperties.builder() .setAppkey(properties.getAppkey()) .setClientId(properties.getClientId()) .setClientSecret(properties.getClientSecret()) .build(); service = new EMService(emProperties); } //创建环信用户 public Boolean createUser(String username,String password) { try { //创建环信用户 service.user().create(username.toLowerCase(), password) .block(); return true; }catch (Exception e) { e.printStackTrace(); log.error("创建环信用户失败~"); } return false; } //添加联系人 public Boolean addContact(String username1,String username2) { try { //创建环信用户 service.contact().add(username1,username2) .block(); return true; }catch (Exception e) { log.error("添加联系人失败~"); } return false; } //删除联系人 public Boolean deleteContact(String username1,String username2) { try { //创建环信用户 service.contact().remove(username1,username2) .block(); return true; }catch (Exception e) { log.error("删除联系人失败~"); } return false; } //发送消息 public Boolean sendMsg(String username,String content) { try { //接收人用户列表 Set<String> set = CollUtil.newHashSet(username); //文本消息 EMTextMessage message = new EMTextMessage().text(content); //发送消息 from:admin是管理员发送 service.message().send("admin","users", set,message,null).block(); return true; }catch (Exception e) { log.error("删除联系人失败~"); } return false; } }
2.业务逻辑
2.1 新用户注册时,连接环形服务,注册环形账号
//注册环信用户 String hxUser = "hx"+user.getId(); Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD); if(create) { user.setHxUser(hxUser); user.setHxPassword(Constants.INIT_PASSWORD); userApi.update(user); }
2.2 老用户登录时,从mysql数据库中拿到环信账号信息并登录环信服务器
@Service public class HuanXinService { @DubboReference private UserApi userApi; /** * 查询当前用户的环信账号 * 1、获取用户id,根据账号规则拼接 * 2、获取用户id,查询用户对象 */ public HuanXinUserVo findHuanXinUser() { Long userId = UserHolder.getUserId(); User user = userApi.findById(userId); if(user == null) { return null; } return new HuanXinUserVo(user.getHxUser(),user.getHxPassword()); } }
标签:return,String,用户,即时,环信,通信,user,服务,public 来源: https://www.cnblogs.com/qaqz/p/16217159.html