websocket更新

This commit is contained in:
2511 2024-09-05 11:58:19 +08:00
parent a951b92370
commit f3907fcbcc
26 changed files with 377 additions and 30 deletions

12
pom.xml
View File

@ -100,6 +100,14 @@
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -122,6 +130,10 @@
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- Pull in as a traditional dependency -->
</dependencies>

View File

@ -5,12 +5,16 @@ import okhttp3.*;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import java.io.IOException;
@SpringBootApplication
@EnableCaching
@EnableScheduling
@MapperScan("generator.mapper")
public class UpsApplication {

View File

@ -0,0 +1,20 @@
package com.nkkj.ups.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("generator.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); // 如果配置多个插件, 切记分页最后添加
// 如果有多数据源可以不配具体类型, 否则都建议配上具体的 DbType
return interceptor;
}
}

View File

@ -0,0 +1,30 @@
package com.nkkj.ups.config;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
//@EnableCaching
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}

View File

@ -0,0 +1,25 @@
package com.nkkj.ups.controller;
import com.nkkj.ups.result.R;
import com.nkkj.ups.service.AlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DataController {
@Autowired
AlarmService alarmService;
@Autowired
@GetMapping("/all")
public R saveData() {
try{
alarmService.UpsAlarm();
}
catch (Exception e){
e.printStackTrace();
}
return R.success();
}
}

View File

@ -0,0 +1,13 @@
package com.nkkj.ups.controller;
import com.nkkj.ups.result.R;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HistoryDataController {
@GetMapping("getHistory")
public R getHistory() {
return null;
}
}

View File

@ -1,7 +1,7 @@
package com.nkkj.ups.controller;
import com.nkkj.ups.result.R;
import com.nkkj.ups.service.impl.LoginServiceImpl;
import com.nkkj.ups.service.LoginService;
import com.nkkj.ups.utils.JWT.JwtUtils;
import generator.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
@Autowired
LoginServiceImpl loginService;
LoginService loginService;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/login")

View File

@ -1,8 +1,22 @@
package com.nkkj.ups.controller;
import com.nkkj.ups.result.R;
import com.nkkj.ups.service.UpsService;
import com.nkkj.ups.service.impl.UpsServiceImpl;
import generator.domain.UpsHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class MqttController {
@Autowired
UpsService upsService;
@PostMapping("/getHistory")
public R getHistory(String id,String ups_id){
List<UpsHistory> upsHistory=upsService.getUpsHistory();
return R.success(upsHistory);
}
}

View File

@ -7,7 +7,7 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class SignController {
@PostMapping
@PostMapping("/sign")
public R sign(){
return R.success();

View File

@ -0,0 +1,10 @@
package com.nkkj.ups.param.request;
import lombok.Data;
@Data
public class GetHistoryParams {
//门店id
private String id;
private String ups_id;
}

View File

@ -0,0 +1,13 @@
package com.nkkj.ups.param.request;
import lombok.Data;
@Data
public class UpsData<T> {
//upsid
private String id;
private String dataType;
private T value;
private String identifier;
private String name;
}

View File

@ -0,0 +1,22 @@
package com.nkkj.ups.schedule;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class IsOnline {
public static Map<String, Long> onlineMap = new ConcurrentHashMap<String, Long>();
@Scheduled(cron = "0/10 * * * * ? ")
public void isOnline() throws InterruptedException {
for (String s : onlineMap.keySet()) {
long now = new Date().getTime();
if(now-onlineMap.get(s)>30) {
System.out.println("超市");
}
}
}
}

View File

@ -27,7 +27,6 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
UserDetailsService userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("2");
String token=request.getHeader("Authorization");
if (token == null || token.isEmpty()) {
// 没有携带 token 放行

View File

@ -0,0 +1,14 @@
package com.nkkj.ups.service;
import com.nkkj.ups.websocket.WsServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AlarmService {
@Autowired
WsServerEndpoint endpoint;
public void UpsAlarm() throws Exception {
endpoint.sendAllUser("测试");
}
}

View File

@ -0,0 +1,9 @@
package com.nkkj.ups.service;
import generator.domain.UpsHistory;
import java.util.List;
public interface UpsService {
List<UpsHistory> getUpsHistory();
}

View File

@ -5,6 +5,7 @@ import com.nkkj.ups.utils.JWT.JwtUtils;
import generator.domain.User;
import generator.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Service;
@ -12,9 +13,15 @@ import org.springframework.stereotype.Service;
public class LoginServiceImpl implements LoginService {
@Autowired
UserMapper userMapper;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public User login(String username, String password) {
redisTemplate.opsForValue().set(username,password);
String value = (String) redisTemplate.opsForValue().get("run_id");
System.out.println(value);
User user=userMapper.selectOneByNameAndPassword(username,password);
return user;
}
}

View File

@ -0,0 +1,20 @@
package com.nkkj.ups.service.impl;
import com.nkkj.ups.service.UpsService;
import generator.domain.UpsHistory;
import generator.mapper.UpsHistoryMapper;
import generator.mapper.UpsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UpsServiceImpl implements UpsService {
@Autowired
UpsHistoryMapper upsHistoryMapper;
@Override
public List<UpsHistory> getUpsHistory() {
return upsHistoryMapper.selectList(null);
}
}

View File

@ -0,0 +1,14 @@
package com.nkkj.ups.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpoint() {
return new ServerEndpointExporter();
}
}

View File

@ -0,0 +1,89 @@
package com.nkkj.ups.websocket;
import com.alibaba.fastjson.JSONObject;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/echo/{id}")
@Component
public class WsServerEndpoint {
public static Map<String,WsServerEndpoint> wsServerEndpointMap = new ConcurrentHashMap<>();
private Session session;
private String id;
// 收到消息
@OnMessage
public void onMessage(String message) throws Exception {
JSONObject jsonObject = JSONObject.parseObject(message);
String id= (String) jsonObject.get("id");
String msg=(String) jsonObject.get("msg");
if (message.equalsIgnoreCase("bye")) {
// 由服务器主动关闭连接状态码为 NORMAL_CLOSURE正常关闭
this.session.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "Bye"));;
return;
}
if(id!=null)
{
if("-1".equals(id))
{
sendAllUser("1");
}
else {
sendToUser(id, msg);
}
}
// this.session.getAsyncRemote().sendText("["+ Instant.now().toEpochMilli() +"] Hello " + message);
}
// 连接打开
@OnOpen
public void onOpen(@PathParam(value = "id") String id, Session session, EndpointConfig endpointConfig){
System.out.println("开启连接");
// 保存 session 到对象
this.session = session;
this.id = id;
wsServerEndpointMap.put(id,this);
}
// 连接关闭
@OnClose
public void onClose(CloseReason closeReason){
wsServerEndpointMap.remove(this);
System.out.println("断开连接");
}
// 连接异常
@OnError
public void onError(Throwable throwable) throws IOException {
System.out.println(throwable);
// 关闭连接状态码为 UNEXPECTED_CONDITION意料之外的异常
this.session.close(new CloseReason(CloseReason.CloseCodes.UNEXPECTED_CONDITION, throwable.getMessage()));
}
public void sendMessage(String message) throws Exception {
this.session.getAsyncRemote().sendText(message);
}
public void sendToUser(String id, String message) throws Exception {
if(wsServerEndpointMap.containsKey(id)){
wsServerEndpointMap.get(id).session.getAsyncRemote().sendText(message);
}
}
public void sendAllUser(String message) throws Exception{
for (String s : wsServerEndpointMap.keySet()) {
wsServerEndpointMap.get(s).sendMessage(message);
}
}
}

View File

@ -5,6 +5,8 @@ import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import lombok.Data;
/**
@ -17,7 +19,7 @@ public class UpsHistory implements Serializable {
/**
*
*/
@TableId
@TableId(type = IdType.AUTO)
private Integer id;
/**
@ -85,6 +87,11 @@ public class UpsHistory implements Serializable {
*/
private String outPower;
/**
*
*/
private Timestamp createTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
@ -113,7 +120,8 @@ public class UpsHistory implements Serializable {
&& (this.getInVol() == null ? other.getInVol() == null : this.getInVol().equals(other.getInVol()))
&& (this.getOutCur() == null ? other.getOutCur() == null : this.getOutCur().equals(other.getOutCur()))
&& (this.getOutFreq() == null ? other.getOutFreq() == null : this.getOutFreq().equals(other.getOutFreq()))
&& (this.getOutPower() == null ? other.getOutPower() == null : this.getOutPower().equals(other.getOutPower()));
&& (this.getOutPower() == null ? other.getOutPower() == null : this.getOutPower().equals(other.getOutPower()))
&& (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()));
}
@Override
@ -134,6 +142,7 @@ public class UpsHistory implements Serializable {
result = prime * result + ((getOutCur() == null) ? 0 : getOutCur().hashCode());
result = prime * result + ((getOutFreq() == null) ? 0 : getOutFreq().hashCode());
result = prime * result + ((getOutPower() == null) ? 0 : getOutPower().hashCode());
result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode());
return result;
}
@ -157,6 +166,7 @@ public class UpsHistory implements Serializable {
sb.append(", outCur=").append(outCur);
sb.append(", outFreq=").append(outFreq);
sb.append(", outPower=").append(outPower);
sb.append(", createTime=").append(createTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();

View File

@ -6,7 +6,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @author 2511
* @description 针对表ups_history的数据库操作Mapper
* @createDate 2024-08-27 14:59:13
* @createDate 2024-08-29 14:57:00
* @Entity generator.domain.UpsHistory
*/
public interface UpsHistoryMapper extends BaseMapper<UpsHistory> {

View File

@ -6,7 +6,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
/**
* @author 2511
* @description 针对表ups_history的数据库操作Service
* @createDate 2024-08-27 14:59:13
* @createDate 2024-08-29 14:57:00
*/
public interface UpsHistoryService extends IService<UpsHistory> {

View File

@ -9,7 +9,7 @@ import org.springframework.stereotype.Service;
/**
* @author 2511
* @description 针对表ups_history的数据库操作Service实现
* @createDate 2024-08-27 14:59:13
* @createDate 2024-08-29 14:57:00
*/
@Service
public class UpsHistoryServiceImpl extends ServiceImpl<UpsHistoryMapper, UpsHistory>

View File

@ -1,6 +1,9 @@
spring.application.name=ups
server.port=8089
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/ups?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
spring.jackson.parser..allow-unquoted-control-chars=true
spring.data.redis.host=127.0.0.1
spring.data.redis.port=6379

View File

@ -19,6 +19,7 @@
<result property="outCur" column="out_cur" jdbcType="VARCHAR"/>
<result property="outFreq" column="out_freq" jdbcType="VARCHAR"/>
<result property="outPower" column="out_power" jdbcType="VARCHAR"/>
<result property="createTime" column="create_time" jdbcType="TIMESTAMP"/>
</resultMap>
<sql id="Base_Column_List">
@ -26,6 +27,6 @@
device_type,status,city_vol,
city_freq,cell_vol,cell_cur,
out_vol,in_vol,out_cur,
out_freq,out_power
out_freq,out_power,create_time
</sql>
</mapper>

View File

@ -1,8 +1,14 @@
package com.nkkj.ups.test;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nkkj.ups.service.AlarmService;
import com.nkkj.ups.utils.JWT.JwtUtils;
import generator.domain.Ups;
import generator.domain.UpsHistory;
import generator.domain.User;
import generator.mapper.UpsHistoryMapper;
import generator.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import okhttp3.MediaType;
@ -24,34 +30,28 @@ import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {
@Autowired
AlarmService alarmService;
@Autowired
private UserMapper userMapper;
@Autowired
private UpsHistoryMapper upsHistoryMapper;
@Autowired
private JwtUtils jwtUtils;
@Test
public void testSelect() throws IOException, InterruptedException {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.build();
Request request1 = new Request.Builder()
.url("https://iot-api.heclouds.com/thingmodel/query-device-property?product_id=Tz9a5iUEkS&device_name=shante")
.addHeader("Authorization","version=2022-05-01&res=products%2FTz9a5iUEkS%2Fdevices%2Fshante&et=2079998482&method=md5&sign=Gf925YWwSO7SAlOKY98l2Q%3D%3D")
.build();
Response response1 = okHttpClient.newCall(request1).execute();
String string = response1.body().string();
System.out.println(string);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url("https://iot-api.heclouds.com/thingmodel/query-device-property?product_id=Tz9a5iUEkS&device_name=shante")
.addHeader("Authorization", "version=2022-05-01&res=products%2FTz9a5iUEkS%2Fdevices%2Fshante&et=2079998482&method=md5&sign=Gf925YWwSO7SAlOKY98l2Q%3D%3D")
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
// OkHttpClient client = new OkHttpClient().newBuilder()
// .build();
// Request request = new Request.Builder()
// .url("https://iot-api.heclouds.com/thingmodel/query-device-property?product_id=Tz9a5iUEkS&device_name=shante")
// .addHeader("Authorization", "version=2022-05-01&res=products%2FTz9a5iUEkS%2Fdevices%2Fshante&et=2079998482&method=md5&sign=Gf925YWwSO7SAlOKY98l2Q%3D%3D")
// .build();
// Response response = client.newCall(request).execute();
// System.out.println(response.body().string());
// HttpClient client = HttpClient.newHttpClient();
//// String urlString="http://localhost:5000";
@ -76,6 +76,24 @@ public class SampleTest {
// List<User> userList = userMapper.selectList(null);
//// Assert.isTrue(5 == userList.size(), "太短");
// userList.forEach(System.out::println);
try{
alarmService.UpsAlarm();
}
catch (Exception e){
e.printStackTrace();
}
UpsHistory upsHistory = new UpsHistory();
upsHistory.setUpsId(3);
upsHistoryMapper.insert(upsHistory);
Page<UpsHistory> page = new Page<>(2,5);
IPage<UpsHistory> ipage =upsHistoryMapper.selectPage(page, null);
List<UpsHistory> list = ipage.getRecords();
list.forEach(System.out::println);
// System.out.println(ipage.getRecords());
// List<UpsHistory> upsHistories = upsHistoryMapper.selectList(null);
// System.out.println(upsHistories);
}
}