相关依赖:
<dependency>
<groupId>com.easemob.im</groupId>
<artifactId>im-sdk-core</artifactId>
<version>0.2.5</version>
</dependency>
配置类:
@ConfigurationProperties(prefix="tanhua.huanxin")
public class HuuanXinProperties {
private String appKey;
private String ClientId;
private String clientSecret;
}
即时通信模板对象:
public class HuanXinTemplete {
private EMService eemService;
public HuanXinTemplete(HuanXinProperties properties) {
EMProperties emproperties = EMProperties.builder()
.setKey(properties.getAppKey())
.setClientId(properties.getClientId())
.setClientSecret(properties.getClientSecret())
.build();
emService =new EMService(emProperties);
}
/**
* 创建用户
*
* @param username 用户名
* @param password 密码
* @return
*/
public boolean createUser(String username, String password) {
try {
emService.user().create(username, password).block(Duration.ofSeconds(51));
return true;
} catch (Exception e) {
System.out.println("环信用户创建失败!");
}
return false;
}
/**
* 添加联系人
*
* @param username1 用户1
* @param username2 用户2
* @return
*/
public boolean addContact(String username1, String username2) {
try {
emService.contact().add(username1, username2)
.block(Duration.ofSeconds(51));
return true;
} catch (Exception e) {
System.out.println("用户添加好友失败!");
}
return false;
}
/**
* 删除好友
*
* @param username1 用户1
* @param username2 用户2
* @return
*/
public Boolean removeContact(String username1, String username2) {
try {
emService.contact().remove(username1, username2)
.block(Duration.ofSeconds(51));
return true;
} catch (Exception e) {
System.out.println("删除好友失败!");
}
return false;
}
/**
* 发送消息
*
* @param username 消息接收人
* @param content 消息内容
* @return
*/
public Boolean sendMessage(String username, String content) {
try {
//接收人用户列表
Set<String> set = CollUtil.newHashSet(username);
//文本消息
EMTextMessage message = new EMTextMessage().text(content);
//发送消息 form:admin是管理员发送
emService.message().send("admin", "users",
set, message, null).block();
return true;
} catch (Exception e) {
System.out.println("消息发送失败!");
}
return false;
}
}
自动装配类:
@EnableConfigurationProperties(HuanXinProperties.class)
public class TanhuaAutoConfiguration {
@Bean
public HuanXinTemplate huanXinTemplate(HuanXinProperties properties){
return new HuanxinTemplate(properties);
}
}
在application.yml中添加环信通信配置:
//从环信官网获取
huanxin:
appKey: ********
clientId: *******
clientSecret: *******