实现一对一聊天
testCompile group: 'junit', name: 'junit', version: '4.12'
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-websocket', version: '2.5.5'
compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.22'
implementation group: 'com.baomidou', name: 'mybatis-plus-boot-starter', version: '3.4.3.4'
implementation group: 'com.h2database', name: 'h2', version: '1.4.200'
server:
port: 8080
spring:
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:test
username: root
password: 1234
schema: classpath:db/schema-h2.sql
data: classpath:db/data-h2.sql
h2:
console:
enabled: true
path: /h2-database
mybatis-plus:
mapper-locations: classpath*:/mapper/*Mapper.xml
type-aliases-package: com.aa.pojo
configuration:
map-underscore-to-camel-case: false
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
DROP TABLE IF EXISTS offline_msg;
CREATE TABLE offline_msg(
id int NOT NULL AUTO_INCREMENT COMMENT '主键id',
fromId int NULL DEFAULT NULL COMMENT '发送者id',
toId int NULL DEFAULT NULL COMMENT '接收者id',
msg varchar(255) NULL DEFAULT NULL COMMENT '消息'
);
@SpringBootApplication
public class App {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(App.class,args);
WebSocket.setApplicationContext(run);
}
}
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("offline_msg")
public class OfflineMsg implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(type = IdType.AUTO)
private String id;
private Integer fromId;
private Integer toId;
private String msg;
}
@Mapper
public interface OfflineMsgMapper extends BaseMapper<OfflineMsg> {
}
@ServerEndpoint("/ws/{uid}")
@Component
@Data
public class WebSocket{
private static ApplicationContext applicationContext;
public static void setApplicationContext(ApplicationContext applicationContext) {
WebSocket.applicationContext = applicationContext;
}
public static OfflineMsgMapper offlineMsgMapper(){
return applicationContext.getBean(OfflineMsgMapper.class);
}
private static int onlineCount = 0;
public static Logger log= LoggerFactory.getLogger(WebSocket.class);
private static ConcurrentHashMap<Integer,Session> mapUS = new ConcurrentHashMap<>();
private static ConcurrentHashMap<Session,Integer> mapSU = new ConcurrentHashMap<>();
public Session session;
@OnOpen
public void onOpen(Session session1, @PathParam("uid") Integer uid){
session=session1;
mapUS.put(uid,session);
mapSU.put(session,uid);
addOnlineCount();
System.out.println("有新连接用户:"+uid+"加入!当前在线人数为:" + getOnlineCount());
List<OfflineMsg> msgs = offlineMsgMapper().selectList(new QueryWrapper<OfflineMsg>().eq("toId", uid));
if (msgs.size()!=0){
offlineMsgMapper().deleteBatchIds(msgs);
log.info("用户"+uid+"上线,推送离线消息");
for (OfflineMsg msg : msgs) {
session.getAsyncRemote().sendText(msg.getFromId()+":"+msg.getMsg());
}
}
}
@OnClose
public void onClose(Session session) {
Integer uid = mapSU.get(session);
mapUS.remove(uid);
mapSU.remove(session);
subOnlineCount();
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount())<