springgateway搭建及整合websocket
一、三个服务的搭建(eureka注册中心,gateway网关,userservice普通服务)a、注册中心搭建1) pom文件<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http:/...
一、三个服务的搭建(eureka注册中心,gateway网关,userservice普通服务)
a、注册中心搭建
1) pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.avie.ltd</groupId>
<artifactId>AvieEurekaServer</artifactId>
<version>1001</version>
<packaging>jar</packaging>
<name>AvieEurekaServer</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<finalName>AvieEurekaServer</finalName>
</build>
</project>
2)application.properties配置文件
server.port=5006
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=${spring.cloud.client.ipAddress}:${server.port}
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
logging.path=log
server.max-http-header-size=2560000
spring.redis.database=0
spring.redis.host=192.168.1.111
spring.redis.password=awy@2018
spring.redis.port=6379
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
#spring.redis.sentinel.master=
#spring.redis.sentinel.nodes=
spring.redis.timeout=60000
jwt.key=zjk
jwt.expireTime=18000
jwt.prikey.path = pri.key
jwt.pubkey.path = pub.key
3)启动类
package com.avie.ltd;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
@EnableEurekaServer
@SpringBootApplication
@EnableRedisHttpSession
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
b、gateway网关服务
1)pom文件
1)pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yq</groupId>
<artifactId>GatewayDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.33</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.1)application.properties
server.port=4444
spring.application.name=gateway-service
spring.cloud.gateway.filter.remove-non-proxy-headers.headers[0]=dummy
spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1(将url去掉第一个前缀(user-service))
spring.cloud.gateway.routes[0].id=apiuser
spring.cloud.gateway.routes[0].predicates[0]=Path=/user-service/**(拦截以user-service开头的url)
spring.cloud.gateway.routes[0].uri=lb://user-service(跳转到在注册中心上名字为user-service的服务)
##实现websocke的配置
spring.cloud.gateway.routes[1].filters[0]=StripPrefix=1
spring.cloud.gateway.routes[1].id=api2user
spring.cloud.gateway.routes[1].predicates[0]=Path=/user-service/**
spring.cloud.gateway.routes[1].uri=lb:ws://user-service(表示支持websocket协议,并转发到user-service中)
2.2)bootstrap.properties
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:5006/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=127.0.0.1:${server.port}
3)启动类GateWayApplication.java
package com.avie.ltd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
@SpringCloudApplication
public class GateWayApplication {
private static final Logger logger = LoggerFactory.getLogger(GateWayApplication.class);
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/baidu")
.uri("http://baidu.com:80/")
)
.route("websocket_route", r -> r.path("/apitopic1/**")
.uri("ws://127.0.0.1:6605"))
.route(r -> r.path("/userapi3/**")
.filters(f -> f.addResponseHeader("X-AnotherHeader", "testapi3"))
.uri("lb://user-service/")
)
.build();
}
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class, args);
logger.info(" Start APIGatewayApplication Done");
}
}
c、普通服务userservice
1)pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yq</groupId>
<artifactId>UserService</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- websocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<!-- websocket -->
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.33</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.1)application.properties
server.port=5555
spring.application.name=user-service
application.token = USER-SERVICE
#log
logging.config=classpath:logback.xml
logging.path=log
2.2)bootstrap.properties
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:5006/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.instance-id=127.0.0.1:${server.port}
3)启动类UserApplication
3)启动类UserApplication
package com.avie.ltd;
import javax.annotation.PostConstruct;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
@EnableHystrix
@EnableCircuitBreaker
@RestController
@RefreshScope
@ServletComponentScan
@EnableScheduling
public class UserApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(UserApplication.class).web(true).run(args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
@PostConstruct
public void init() {
System.out.println("系统初始化......");
}
}
4)实现websocket的一些配置
4.1 WebSocketAutoConfig.java
package com.avie.ltd.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketAutoConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/user-service") //开启/bullet端点
.setAllowedOrigins("*") //允许跨域访问
.withSockJS(); //使用sockJS
}
// @Override
// public void configureMessageBroker(MessageBrokerRegistry registry) {
// registry.enableSimpleBroker("/toAll"); //订阅Broker名称
// }
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// //向客户端发送信息时,destination的前缀必须是配置中的topic和teleconference
// config.enableSimpleBroker("/topic","/teleconference");
// //客户端向服务端发起请求时,必须以tele为前缀
// config.setApplicationDestinationPrefixes("/tele");
// //服务器向客户端发起一对一信息时,必须以teleconference为前缀
// config.setUserDestinationPrefix("/teleconference/");
}
}
4.2TeleWebSocketManager.java
package com.avie.ltd.entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Service;
@Service
public class TeleWebSocketManager {
private SimpMessageSendingOperations template;
@Autowired
public TeleWebSocketManager(SimpMessageSendingOperations template) {
this.template = template;
}
public void sendToUser(String userName,String destination,Object payload){
template.convertAndSendToUser(userName,destination,payload);
}
public void send(String destination,Object payload){
template.convertAndSend(destination,payload);
}
}
4.3TbCourseUserEnterpriseController.java
4.3TbCourseUserEnterpriseController.java
package com.avie.ltd.controller;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.avie.ltd.entity.TeleWebSocketManager;
@RestController
@RequestMapping(value = "/user")
public class TbCourseUserEnterpriseController{
@Resource
private TeleWebSocketManager teleWebSocketManager;
@RequestMapping(value = "/users/2", method = {RequestMethod.POST,RequestMethod.GET})
public String user(){
return "abcd";
}
//单对单发送
@RequestMapping(value="/sendToOne", produces = {"application/json; charset=utf-8"},method=RequestMethod.GET)
public String sendToOne(String username){
teleWebSocketManager.send("/toAll/"+username, username);
return "成功";
}
}
5.前端连接websocket
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>h2</title>
</head>
<body onload="disconnect()">
<noscript>
<h2 style="color:#ff0000">貌似你的浏览器不支持websocket</h2>
</noscript>
<div>
<div>
<button id="connect" onclick="connect()">连接</button>
<button id="disconnect" onclick="disconnect();">断开连接</button>
</div>
<div id="conversationDiv">
<label>输入你的名字</label> <input type="text" id="name" />
<br>
<label>输入消息</label> <input type="text" id="messgae" />
<button id="send" onclick="send();">发送</button>
<p id="response"></p>
</div>
</div>
<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>
<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var stompClient = null;
//gateway网关的地址
var host="http://127.0.0.1:4444";
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
$('#response').html();
}
function connect() {
//地址+端点路径,构建websocket链接地址
var socket = new SockJS(host+'/user-service/user-service');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
setConnected(true);
console.log('Connected:' + frame);
//监听一个具有自己信息的对列(/toAll/id)
stompClient.subscribe('/toAll/3', function(response) {
showResponse(response.body);
});
//监听一个所有消息的对列
stompClient.subscribe('/toAll/bulletScreen', function(response) {
showResponse(response.body);
});
});
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
setConnected(false);
console.log("Disconnected");
}
function send() {
var name = $('#name').val();
var message = $('#messgae').val();
//发送消息的路径
stompClient.send("/chat", {}, JSON.stringify({username:name,message:message}));
}
function showResponse(message) {
var response = $('#response');
response.html(message);
}
</script>
</body>
</html>
二、实现gateway转发效果
1、通过服务本身端口调用http://localhost:5555/user/users/2
2、通过网关转发http://localhost:4444/user-service/user/users/2
三、实现websocket转发
1、对所有人发送消息:h1发送消息,h1,h2和h3接收到了消息(三个页面都订阅了相同的对列)
2、点对点发送消息:向订阅了/toAll/3的对列发送消息,则只有订阅了/toAll/3的h1会收到消息
调接口:http://localhost:5555/user/sendToOne?username=3
可以通过username参数向指定的人发送消息
附源代码下载链接:https://download.csdn.net/download/qq_41833449/20266005
普通java项目通过项目端口实现websocket连接https://blog.csdn.net/qq_41833449/article/details/88822990
更多推荐
所有评论(0)