一直没有用过websocket,今天出个需求,需要加个聊天模块,找到这篇博客 https://www.jianshu.com/p/47bc85b21912,照着代码运行了一下,了解一下
首先加入依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!-- 静态资源 -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>webjars-locator</artifactId>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>sockjs-client</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>stomp-websocket</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.1.0</version>
</dependency>
由于这个项目加入了security
首先来配置一下security
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AnyUserDetailsService anyUserDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.anyUserDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/webjars/**", "/register", "/api/common/**", "/image/**", "/user/**").permitAll()
.anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/chat", true)
.permitAll().and().logout().permitAll().and().csrf().disable();
}
}
然后配置security的用户
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import java.util.Collection;
public class UserPrincipal extends User {
private static final long serialVersionUID = -4735218819792872573L;
private String nickname;
private String avatar;
public UserPrincipal(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public UserPrincipal(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
}
用户信息
import com.lijia.websocket.mongo.model.User;
import com.lijia.websocket.mongo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class AnyUserDetailsService implements UserDetailsService {
private final static String ROLE_TAG = "ROLE_USER";
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.getByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("用户不存在");
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(ROLE_TAG));
// 用户认证(用户名,密码,权限)
UserPrincipal userPrincipal = new UserPrincipal(username, user.getPassword(), authorities);
userPrincipal.setNickname(user.getNickname());
userPrincipal.setAvatar(user.getAvatar());
return userPrincipal;
}
}
然后 配置websocket
@Configuration
@EnableWebSocketMessageBroker
@Log4j
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/any-socket").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry messageBrokerRegistry) {
messageBrokerRegistry.setApplicationDestinationPrefixes("/app");
messageBrokerRegistry.enableSimpleBroker("/topic", "/queue");
}
@Override
public void configureWebSocketTransport(final WebSocketTransportRegistration registration) {
registration.addDecoratorFactory(new WebSocketHandlerDecoratorFactory() {
@Override
public WebSocketHandler decorate(final WebSocketHandler handler) {
return new WebSocketHandlerDecorator(handler) {
@Override
public void afterConnectionEstablished(final WebSocketSession session) throws Exception {
String username = session.getPrincipal().getName();
log.info("online: " + username);
super.afterConnectionEstablished(session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus)
throws Exception {
String username = session.getPrincipal().getName();
log.info("offline: " + username);
super.afterConnectionClosed(session, closeStatus);
}
};
}
});
super.configureWebSocketTransport(registration);
}
}
主要聊天代码是
一个是群聊消息,一个是单聊消息。
这个项目直接使用map存储数据的,没用到数据库。
再看看聊天页面
首先用创建一个SockJS对象,地址是
/any-socket
,这个和Socket配置中的一样。然后下面订阅了两个主题,/topic/notice
和/user/topic/chat
,对应着上图中的all方法
和chat方法
中发送的主题。在Application启动类中加上
@EnableWebSocket
。启动类,我这打开3个浏览器,每个里面都去注册用户然后登陆。
全部发送消息
2和3加好友
2和3互相发消息,1收不到
大体就是通过websocket发布一些固定的topic,然后页面需要订阅这个topic,有消息就推送。
代码用作者博客里面的 https://github.com/ChinaSilence/any-chat就行。
我还是放到了自己练习项目 https://github.com/lijiaccy/springboot-sharding-table,在websocket文件夹下
网友评论