• 微信小程序实现lot开发08 项目主体业务前后端实现


    主体业务:订座位,下单,时间过期之后自动回收座位,控制座位灯与插座,控制门禁。

    微信小程序页面图片:

     实现逻辑主体在springboot后端代码:

    直接挂代码:有不理解和需要帮助的评论区留言,我会及时回复。

    实体层:

    1. import lombok.Data;
    2. @Data
    3. public class Device {
    4. private String Id;
    5. private boolean State;
    6. private boolean Lock;
    7. private String Info;
    8. /*输出口号*/
    9. private int outSign;
    10. /*设备配置端口号*/
    11. private int hostPort;
    12. /*设备电源状态*/
    13. private boolean power;
    14. /*区号*/
    15. private char areaCode;
    16. }
    17. @Data
    18. public class DeviceUsePrice {
    19. private String deviceId;
    20. private Integer receipt;
    21. private Integer deviceTime;
    22. private String info;
    23. }
    24. @Data
    25. public class Door {
    26. private int Id;
    27. private int outSign;
    28. private int serverPort;
    29. }
    30. @Data
    31. public class FromInfo {
    32. private String info;
    33. private Date date;
    34. }
    35. @Data
    36. public class User {
    37. private String Id;
    38. private String Name;
    39. private Integer Amount;
    40. private String Phone;
    41. private String password;
    42. }
    43. @Data
    44. public class UserDevice {
    45. private String userId;
    46. private Integer useTime;
    47. private String deviceId;
    48. private Integer receipt;
    49. private String orderTime;
    50. private boolean orderState;
    51. }

     mapper层

    1. import com.hlc.entity.Device;
    2. import org.apache.ibatis.annotations.Mapper;
    3. import org.apache.ibatis.annotations.Param;
    4. import org.apache.ibatis.annotations.Select;
    5. import org.apache.ibatis.annotations.Update;
    6. import java.util.List;
    7. @Mapper
    8. public interface DeviceMapper {
    9. @Select("select * from getmsqlconnection.device where areaCode=#{areaCode}")
    10. List findDeviceByArea(@Param("areaCode") char areaCode);
    11. @Update("update getmsqlconnection.device set `State` = 0 , `Lock` = 1 where `Id`=#{Id}")
    12. boolean updateDeviceStateByDeviceId(@Param("Id") String Id);
    13. @Update("update getmsqlconnection.device set `State` = 1 , `Lock` = 0 where `Id`=#{Id}")
    14. boolean freeDeviceByDeviceId(@Param("Id") String Id);
    15. @Select("select `Lock` from getmsqlconnection.device where `Id`=#{Id}")
    16. boolean findDeviceLockByDeviceId(@Param("Id")String Id);
    17. @Select("select outSign from getmsqlconnection.device where Id=#{Id}")
    18. int findOutSignByDeviceId(@Param("Id")String Id);
    19. @Select("select hostPort from getmsqlconnection.device where Id=#{Id}")
    20. int findHostPortByDeviceId(@Param("Id")String Id);
    21. @Update("update getmsqlconnection.device set power = 1 where Id=#{Id}")
    22. boolean openDevicePowerByDeviceId(@Param("Id")String Id);
    23. @Update("update getmsqlconnection.device set power = 0 where Id=#{Id}")
    24. boolean downDevicePowerByDeviceId(@Param("Id")String Id);
    25. @Select("select power from getmsqlconnection.device where Id=#{Id}")
    26. boolean findDevicePowerByDeviceId(@Param("Id")String Id);
    27. }
    28. @Mapper
    29. public interface DeviceUsePriceMapper {
    30. @Select("select * from getmsqlconnection.device_use_price where deviceId=#{deviceId}")
    31. List findDeviceUsePriceByDeviceId(@Param("deviceId")String deviceId);
    32. }
    33. @Mapper
    34. public interface DoorMapper {
    35. @Select("select * from getmsqlconnection.door where Id=1 ")
    36. Door findDoor();
    37. }
    38. @Mapper
    39. public interface FromInfoMapper {
    40. @Select("select date,info from getmsqlconnection.from_info")
    41. List findAllFromInfo();
    42. }
    43. @Mapper
    44. public interface UserDeviceMapper {
    45. @Insert("insert into getmsqlconnection.user_device values (#{userDevice.userId},#{userDevice.useTime},#{userDevice.deviceId},#{userDevice.receipt},#{userDevice.orderTime},#{userDevice.orderState})")
    46. boolean InsertUserDevice(@Param("userDevice")UserDevice userDevice);
    47. @Select("select * from getmsqlconnection.user_device where userId=#{userId}")
    48. List findUserDeviceByUserId(@Param("userId")String userId);
    49. @Update("update getmsqlconnection.user_device set useTime = 0 where useTime!=0 and deviceId=#{deviceId}")
    50. boolean updateExOrder(@Param("deviceId")String deviceId);
    51. // 用户使用时间在缓存过期时会被设置为0;所以当前不为0的使用时间就是用户可以使用设备的凭证
    52. @Select("select deviceId from getmsqlconnection.user_device where useTime != 0 and userId=#{userId}")
    53. String findDeviceIdByUserId(@Param("userId")String userId);
    54. }
    55. @Mapper
    56. public interface UserMapper {
    57. // 登录
    58. @Select("select password from getmsqlconnection.user where Id=#{Id}")
    59. String login(@Param("Id") String Id,@Param("password") String password);
    60. // 注册
    61. @Insert("insert into getmsqlconnection.user values(#{user.Id},#{user.Name},#{user.Phone},#{user.Amount},#{user.password})")
    62. Boolean register(@Param("user") User user);
    63. // 修改密码
    64. @Update("update getmsqlconnection.user set password=#{password} where Id=#{Id}")
    65. Boolean updatePassword(@Param("Id") String Id,@Param("password") String password);
    66. }

     Servcie层(无非是mapper层的注入语接口的重塑,便于解耦与业务的拓展)

    controller层(嵌套工具组件)

    deviceController

    1. package com.hlc.controller;/*
    2. User: 黄林春
    3. Date: 2022/7/13
    4. Time: 周三
    5. Project_Name: springDemo712
    6. */
    7. import com.hlc.common.R;
    8. import com.hlc.entity.Device;
    9. import com.hlc.service.DeviceService;
    10. import com.hlc.service.UserDeviceService;
    11. import com.hlc.utils.NetAndIoController;
    12. import com.hlc.utils.NetFactory;
    13. import org.springframework.beans.factory.annotation.Autowired;
    14. import org.springframework.web.bind.annotation.*;
    15. import java.util.List;
    16. @RestController(value = "DeviceController")
    17. public class DeviceController {
    18. @Autowired
    19. private DeviceService deviceService;
    20. /**
    21. * --------------------------------------------查询全部设备信息------------------------------------------------------/
    22. */
    23. @GetMapping("/findDeviceByArea")
    24. @ResponseBody
    25. public R findDeviceByArea(@RequestParam("areaCode") char areaCode) {
    26. List deviceList = deviceService.findDeviceByArea(areaCode);
    27. R r = new R<>();
    28. r.setCode(1);
    29. r.setData(deviceList);
    30. r.setMsg("查询全部设备信息成功!");
    31. return r;
    32. }
    33. /***
    34. * ---------------------------------查询设备锁状态(锁为false就是可读不可写)-------------------------------------------/
    35. */
    36. @GetMapping("/findDeviceLockByDeviceId")
    37. @ResponseBody
    38. public R findDeviceLockByDeviceId(@RequestParam("deviceId") String deviceId) {
    39. try {
    40. /*异常只有可能在这里发生*/
    41. boolean lock = deviceService.findDeviceLockByDeviceId(deviceId);
    42. if (lock) {
    43. return R.error("设备已被使用,现在不可下单");
    44. }
    45. return R.success(true);
    46. } catch (Exception e) {
    47. return R.error("设备锁无法查询");
    48. }
    49. }
    50. /**
    51. * --------------------------------------------电源控制-------------------------------------------------------------/
    52. */
    53. @Autowired
    54. private NetFactory netFactory;
    55. @Autowired
    56. private UserDeviceService userDeviceService;
    57. @GetMapping("/updateDevicePower")
    58. @ResponseBody
    59. public R updateDevicePower(@RequestParam("deviceId") String deviceId, @RequestParam("userId") String userId) {
    60. R r = new R<>();
    61. /**查询当前用户是否具备未过期订单*/
    62. String V = userDeviceService.findDeviceIdByUserId(userId);
    63. try {
    64. if (V != null) {
    65. NetAndIoController netAndIoController = netFactory.getNetAndIoController();
    66. /**将当前设备对应的输出口号赋值给out口标识*/
    67. netAndIoController.outSign = deviceService.findOutSignByDeviceId(deviceId);
    68. /**将分配的主机端口赋值给port标识*/
    69. netAndIoController.serverPort = deviceService.findHostPortByDeviceId(deviceId);
    70. /**查询当前设备的电源通断标识power*/
    71. boolean power = deviceService.findDevicePowerByDeviceId(deviceId);
    72. if (power) {
    73. netAndIoController.TcpConnection();
    74. /**如果电源状态为通电true,则执行关闭电源的指令方法*/
    75. netAndIoController.sendDownControllerMsg();
    76. deviceService.downDevicePowerByDeviceId(deviceId);
    77. } else {
    78. netAndIoController.TcpConnection();
    79. /**如果电源状态为false,则执行开电源的指令方法*/
    80. netAndIoController.sendOpenControllerMsg();
    81. deviceService.openDevicePowerByDeviceId(deviceId);
    82. }
    83. // 因为开关座位电源的频率比开门禁的概率高
    84. // netAndIoController.shutClient();
    85. return R.success(true);
    86. }
    87. return R.error("当前用户订单过期");
    88. } catch (Exception e) {
    89. return R.error("TCP连接失败");
    90. }
    91. }
    92. }
    93. DeviceUsePriceController

      1. package com.hlc.controller;/*
      2. User: 黄林春
      3. Date: 2022/7/14
      4. Time: 周四
      5. Project_Name: springDemo712
      6. */
      7. import com.hlc.common.R;
      8. import com.hlc.entity.DeviceUsePrice;
      9. import com.hlc.service.DeviceUsePriceService;
      10. import org.springframework.beans.factory.annotation.Autowired;
      11. import org.springframework.web.bind.annotation.RequestMapping;
      12. import org.springframework.web.bind.annotation.RequestParam;
      13. import org.springframework.web.bind.annotation.ResponseBody;
      14. import org.springframework.web.bind.annotation.RestController;
      15. import java.util.List;
      16. @RestController(value = "DeviceUsePriceController")
      17. public class DeviceUsePriceController {
      18. @Autowired
      19. private DeviceUsePriceService deviceUsePriceService;
      20. /**
      21. * 查询某一号设备的设备价格表
      22. * @param deviceId
      23. * @return
      24. */
      25. @RequestMapping("/findDeviceUsePriceByDeviceId")
      26. @ResponseBody
      27. public R findDeviceUsePriceByDeviceId(@RequestParam("deviceId")String deviceId){
      28. R r = new R<>();
      29. try{
      30. List priceList = deviceUsePriceService.findDeviceUsePriceByDeviceId(deviceId);
      31. r.setData(priceList);
      32. r.setCode(1);
      33. r.setMsg("价格表查询成功");
      34. return r;
      35. }catch (Exception e){
      36. r.setCode(0);
      37. r.setMsg("价格表查询错误");
      38. return r;
      39. }
      40. }
      41. }
      42.  DoorController

        1. package com.hlc.controller;/*
        2. User: 黄林春
        3. Date: 2022/7/21
        4. Time: 周四
        5. Project_Name: springDemo712
        6. */
        7. import com.hlc.common.R;
        8. import com.hlc.entity.Door;
        9. import com.hlc.service.DoorService;
        10. import com.hlc.service.UserDeviceService;
        11. import com.hlc.utils.NetAndIoController;
        12. import com.hlc.utils.NetFactory;
        13. import org.springframework.beans.factory.annotation.Autowired;
        14. import org.springframework.web.bind.annotation.GetMapping;
        15. import org.springframework.web.bind.annotation.RequestParam;
        16. import org.springframework.web.bind.annotation.ResponseBody;
        17. import org.springframework.web.bind.annotation.RestController;
        18. @RestController
        19. public class DoorController {
        20. @Autowired
        21. private DoorService doorService;
        22. @Autowired
        23. private UserDeviceService userDeviceService;
        24. @Autowired
        25. private NetFactory netFactory;
        26. @GetMapping("/doorController")
        27. @ResponseBody
        28. public R doorController(@RequestParam("userId")String userId){
        29. R r = new R<>();
        30. try {
        31. System.out.println("----------查询该用户是否可以使用门禁------");
        32. String deviceId = userDeviceService.findDeviceIdByUserId(userId);
        33. System.out.println("---------拥有订单"+deviceId+"可以使用门禁--------");
        34. if (deviceId != null){
        35. NetAndIoController netAndIoController = netFactory.getNetAndIoController();
        36. System.out.println("---------门禁控制类实现成功-----------");
        37. Door door = doorService.findDoor();
        38. netAndIoController.outSign = door.getOutSign();
        39. netAndIoController.serverPort = door.getServerPort();
        40. System.out.println("----------开始尝试连接门禁TCP----------------");
        41. netAndIoController.TcpConnection();
        42. netAndIoController.sendDelayOpenControllerMsg();
        43. System.out.println("-------------开门成功-----------------");
        44. netAndIoController.shutClient();
        45. r.setMsg("开门成功");
        46. r.setCode(1);
        47. return r;
        48. }
        49. return R.error("开门失败");
        50. }catch (Exception e){
        51. System.out.println("----------------开门异常---------------");
        52. return R.error("开门失败");
        53. }
        54. }
        55. }

         FromInfoController

        1. package com.hlc.controller;/*
        2. User: 黄林春
        3. Date: 2022/7/15
        4. Time: 周五
        5. Project_Name: springDemo712
        6. */
        7. import com.hlc.common.R;
        8. import com.hlc.entity.FromInfo;
        9. import com.hlc.service.FromInfoService;
        10. import org.springframework.beans.factory.annotation.Autowired;
        11. import org.springframework.web.bind.annotation.GetMapping;
        12. import org.springframework.web.bind.annotation.ResponseBody;
        13. import org.springframework.web.bind.annotation.RestController;
        14. import java.util.List;
        15. @RestController
        16. public class FromInfoController {
        17. @Autowired
        18. private FromInfoService fromInfoService;
        19. /***
        20. * 查询全部公告
        21. * @return
        22. */
        23. @GetMapping("/findAllFromInfo")
        24. @ResponseBody
        25. public R findAllFromInfo() {
        26. R r = new R<>();
        27. try {
        28. List fromInfoList = fromInfoService.findAllFromInfo();
        29. r.setData(fromInfoList);
        30. r.setCode(1);
        31. r.setMsg("查询公告成功");
        32. return r;
        33. } catch (Exception e) {
        34. return R.error("查询公告失败");
        35. }
        36. }
        37. }
        38. usercontroller

          1. package com.hlc.controller;/*
          2. User: 黄林春
          3. Date: 2022/7/12
          4. Time: 周二
          5. Project_Name: springDemo712
          6. */
          7. import com.hlc.common.R;
          8. import com.hlc.entity.User;
          9. import com.hlc.service.UserService;
          10. import org.springframework.beans.factory.annotation.Autowired;
          11. import org.springframework.web.bind.annotation.RequestMapping;
          12. import org.springframework.web.bind.annotation.RequestParam;
          13. import org.springframework.web.bind.annotation.ResponseBody;
          14. import org.springframework.web.bind.annotation.RestController;
          15. import org.springframework.web.servlet.ModelAndView;
          16. import java.sql.SQLException;
          17. @RestController(value = "UserController")
          18. public class UserController {
          19. @Autowired
          20. private UserService userService;
          21. /**
          22. * 登录
          23. * @param Id
          24. * @param password
          25. * @return
          26. */
          27. @RequestMapping("/login")
          28. public R userLogin(@RequestParam("Id")String Id, @RequestParam("password")String password){
          29. // System.out.println("-------------"+Id+"||"+password+"--------------------");
          30. if (Id == null || password == null){
          31. return R.error("输入完整的账号密码!");
          32. }
          33. try {
          34. String userLogin = userService.userLogin(Id, password);
          35. // System.out.println("-------------"+userLogin+"----------");
          36. if (!userLogin.equals(password)){
          37. throw new SQLException("账号密码错误!");
          38. }
          39. return R.success(true);
          40. }catch (Exception e){
          41. return R.error("登录失败!");
          42. }
          43. }
          44. /**
          45. * 注册
          46. * @param Id
          47. * @param Name
          48. * @param Phone
          49. * @param password
          50. * @return
          51. */
          52. @RequestMapping("/register")
          53. @ResponseBody
          54. public R UserRegister(@RequestParam("Id") String Id,@RequestParam("Name")String Name,@RequestParam("Phone")String Phone,@RequestParam("password")String password){
          55. System.out.println("-----------微信小程序访问------------");
          56. if (Id == null || password == null)
          57. return R.error("请填写完整的用户信息!");
          58. String password1 = null;
          59. try {
          60. password1 = userService.userLogin(Id,password);
          61. }catch (Exception e){
          62. System.out.println("该账户没有注册过!");
          63. throw e;
          64. }
          65. try{
          66. if (password1 != null)
          67. throw new Exception("该账户名已经被使用!");
          68. User user = new User();
          69. user.setId(Id);
          70. user.setName(Name);
          71. user.setAmount(0);
          72. user.setPhone(Phone);
          73. user.setPassword(password);
          74. boolean userRegister = userService.UserRegister(user);
          75. if (!userRegister){
          76. throw new Exception("注册失败!");
          77. }
          78. return R.success(true);
          79. }catch (Exception e){
          80. return R.error("注册失败!");
          81. }
          82. }
          83. }

          UserDeviceController

          1. package com.hlc.controller;/*
          2. User: 黄林春
          3. Date: 2022/7/14
          4. Time: 周四
          5. Project_Name: springDemo712
          6. */
          7. import com.hlc.common.R;
          8. import com.hlc.entity.UserDevice;
          9. import com.hlc.service.DeviceService;
          10. import com.hlc.service.UserDeviceService;
          11. import com.hlc.utils.JedisUtil;
          12. import org.apache.ibatis.annotations.Param;
          13. import org.springframework.beans.factory.annotation.Autowired;
          14. import org.springframework.transaction.annotation.Transactional;
          15. import org.springframework.transaction.interceptor.TransactionAspectSupport;
          16. import org.springframework.web.bind.annotation.*;
          17. import java.util.List;
          18. @RestController(value = "UserDeviceController")
          19. public class UserDeviceController {
          20. @Autowired
          21. private UserDeviceService userDeviceService;
          22. @Autowired
          23. private DeviceService deviceService;
          24. @Autowired
          25. private JedisUtil jedisUtil;
          26. /**
          27. * 用户支付后回调
          28. * 修改设备信息以及在订单记录中插入一条记录
          29. *
          30. * @param receipt
          31. * @param deviceId
          32. * @param userId
          33. * @param useTime
          34. * @return
          35. */
          36. @RequestMapping("/insertUserDevice")
          37. @ResponseBody
          38. /**设置事务回滚(一般用于多表操作,单表使用异常捕获就可以实现)*/
          39. @Transactional(rollbackFor = Exception.class)
          40. public R InsertUserDevice(@Param("receipt") Integer receipt, @Param("deviceId") String deviceId,
          41. @Param("userId") String userId, @Param("useTime") Integer useTime, @Param("orderTime") String orderTime) {
          42. try {
          43. System.out.println("-------------生成订单对象---------------");
          44. UserDevice userDevice = new UserDevice();
          45. userDevice.setDeviceId(deviceId);
          46. userDevice.setUserId(userId);
          47. userDevice.setUseTime(useTime);
          48. /**
          49. * 此时应该在插入这条用户使用记录的地方设置redis缓存键值对,
          50. * key是用户id+设备id,value是时间。
          51. * */
          52. System.out.println("--------------插入缓存------------------");
          53. jedisUtil.InsertOrderServerListener(deviceId,userId,useTime);
          54. System.out.println("--------缓存成功,继续装箱--------");
          55. userDevice.setReceipt(receipt);
          56. userDevice.setOrderTime(orderTime);
          57. userDevice.setOrderState(true);
          58. System.out.println("-----------装箱完毕,校验成功后缓存记录------------");
          59. boolean insertUserDevice = userDeviceService.InsertUserDevice(userDevice);
          60. boolean updateDeviceState = deviceService.updateDeviceStateByDeviceId(deviceId);
          61. if (!insertUserDevice || !updateDeviceState) {
          62. throw new Exception("插入订单记录失败");
          63. }
          64. return R.success(true);
          65. } catch (Exception e) {
          66. /**回滚支持*/
          67. TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
          68. return R.error("添加新的订单失败");
          69. }
          70. }
          71. /***
          72. * 查询某一用户的全部使用记录
          73. * 用户可查看自己的消费记录
          74. * @param userId
          75. * @return
          76. */
          77. @RequestMapping("/findUserDeviceByUserId")
          78. @ResponseBody
          79. public R findUserDeviceByUserId(@RequestParam("userId") String userId) {
          80. R r = new R<>();
          81. try{
          82. List userDeviceList = userDeviceService.findUserDeviceByUserId(userId);
          83. r.setData(userDeviceList);
          84. r.setCode(1);
          85. r.setMsg("查询消费记录成功");
          86. return r;
          87. }catch (Exception e){
          88. return R.error("查询失败");
          89. }
          90. }
          91. /**
          92. * 校验用户订单是否过期
          93. * @param userId
          94. * @return deviceId
          95. */
          96. @GetMapping("/findUserTime")
          97. @ResponseBody
          98. public R findUserTime(@RequestParam("userId")String userId){
          99. R r = new R<>();
          100. try{
          101. String deviceId= userDeviceService.findDeviceIdByUserId(userId);
          102. System.out.println("--------查询用户是否具备使用权-----------");
          103. r.setData(deviceId);
          104. r.setMsg("查询成功");
          105. r.setCode(1);
          106. return r;
          107. }catch (Exception e){
          108. return R.error("该用户没有可用订单");
          109. }
          110. }
          111. }
          112. 通用响应对象

            1. package com.hlc.common;
            2. /*
            3. User: 黄林春
            4. Date: 2022/7/12
            5. Time: 周二
            6. Project_Name: springDemo712
            7. */
            8. import lombok.Data;
            9. import java.util.HashMap;
            10. import java.util.Map;
            11. /**组件返回通用类,设定返回码与消息与返回结果的封装*/
            12. @Data
            13. public class R {
            14. //响应码
            15. private Integer code;
            16. //响应消息
            17. private String msg;
            18. private T data;
            19. private Map map = new HashMap();
            20. public static R success(T object) {
            21. R r = new R();
            22. r.data = object;
            23. r.code = 1;
            24. return r;
            25. }
            26. public static R error(String msg) {
            27. R r = new R();
            28. r.msg = msg;
            29. r.code = 0;
            30. return r;
            31. }
            32. public R add(String key, Object value) {
            33. this.map.put(key, value);
            34. return this;
            35. }
            36. }

            redis控制组件(缓存实现的目的主要是过期监听,普通活动限期的实现,也可以自加缓存登录减少数据库压力)

            单例jedispool的创建

            1. package com.hlc.utils;/*
            2. User: 黄林春
            3. Date: 2022/7/19
            4. Time: 周二
            5. Project_Name: springDemo712
            6. */
            7. import org.springframework.stereotype.Component;
            8. import redis.clients.jedis.Jedis;
            9. import redis.clients.jedis.JedisPool;
            10. import redis.clients.jedis.JedisPoolConfig;
            11. @Component
            12. public class JedisFactory {
            13. private static JedisPool jedisPool = null;
            14. public static JedisPool getJedisPool() {
            15. if (jedisPool == null) {
            16. synchronized (JedisFactory.class) {
            17. if (jedisPool == null) {
            18. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            19. jedisPoolConfig.setMaxIdle(150);
            20. jedisPoolConfig.setMaxTotal(200);
            21. jedisPoolConfig.setTestOnBorrow(false);
            22. jedisPoolConfig.setBlockWhenExhausted(true);
            23. jedisPool = new JedisPool(jedisPoolConfig, "192.168.100.150", 6379);
            24. }
            25. }
            26. }
            27. return jedisPool;
            28. }
            29. public void release(Jedis jedis, JedisPool jedisPool) {
            30. if (jedisPool != null) {
            31. jedis.close();
            32. }
            33. }
            34. }

            jedisuntil对缓存数据库实现插入一对时效性键值对

            1. package com.hlc.utils;/*
            2. User: 黄林春
            3. Date: 2022/7/19
            4. Time: 周二
            5. Project_Name: springDemo712
            6. */
            7. import org.springframework.stereotype.Component;
            8. import redis.clients.jedis.Jedis;
            9. import redis.clients.jedis.JedisPool;
            10. @Component
            11. public class JedisUtil {
            12. static JedisPool jedisPool = JedisFactory.getJedisPool();
            13. static Jedis jedis = jedisPool.getResource();
            14. /*用户下单对应的时间与用户的Id与设备Id, key:设备Id , value: 用户Id*/
            15. public void InsertOrderServerListener(String deviceId,String userId,Integer time){
            16. jedis.auth("hlc");
            17. try {
            18. System.out.println("--------------" + deviceId + "订单开始计时----------------");
            19. /**向缓存中插入这一对订单键值对,以秒为单位计时*/
            20. jedis.setex(deviceId, time*60*60 , userId);
            21. }catch (Exception e){
            22. System.out.println("------------------缓存异常---------------");
            23. }
            24. jedis.close();
            25. }
            26. }

            缓存远程监听配置

            1. package com.hlc.utils;/*
            2. User: 黄林春
            3. Date: 2022/7/19
            4. Time: 周二
            5. Project_Name: springDemo712
            6. */
            7. import org.springframework.cache.annotation.CachingConfigurerSupport;
            8. import org.springframework.context.annotation.Bean;
            9. import org.springframework.context.annotation.Configuration;
            10. import org.springframework.data.redis.connection.RedisConnectionFactory;
            11. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
            12. /**redis缓存配置类*/
            13. @Configuration
            14. public class RedisConfig extends CachingConfigurerSupport {
            15. @Bean
            16. RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
            17. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
            18. container.setConnectionFactory(connectionFactory);
            19. return container;
            20. }
            21. }

            缓存监听,键值过期出发业务

            1. package com.hlc.utils;/*
            2. User: 黄林春
            3. Date: 2022/7/19
            4. Time: 周二
            5. Project_Name: springDemo712
            6. */
            7. import com.hlc.service.DeviceService;
            8. import com.hlc.service.UserDeviceService;
            9. import org.springframework.beans.factory.annotation.Autowired;
            10. import org.springframework.data.redis.connection.Message;
            11. import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
            12. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
            13. import org.springframework.stereotype.Component;
            14. @Component
            15. public class RedisListener extends KeyExpirationEventMessageListener {
            16. @Autowired
            17. private UserDeviceService userDeviceService;
            18. @Autowired
            19. private DeviceService deviceService;
            20. @Autowired
            21. private NetFactory netFactory;
            22. public RedisListener(RedisMessageListenerContainer listenerContainer) {
            23. super(listenerContainer);
            24. }
            25. /**
            26. * 针对redis数据失效事件,进行数据处理
            27. *
            28. * @param message
            29. * @param pattern
            30. */
            31. @Override
            32. public void onMessage(Message message, byte[] pattern) {
            33. /**当名为expiredKey的键值对过期了,会把key返回,而不会将value返回*/
            34. String expiredKey = message.toString();
            35. try {
            36. /**首先修改订单使用时间为0*/
            37. boolean updateExOrder = userDeviceService.updateExOrder(expiredKey);
            38. /**其次将设备的锁装置与设备状态释放掉*/
            39. deviceService.freeDeviceByDeviceId(expiredKey);
            40. /**最后向设备查询设备电源状态,如果状态为开则发送关闭指令*/
            41. boolean power = deviceService.findDevicePowerByDeviceId(expiredKey);
            42. if (power) {
            43. NetAndIoController netAndIoController = netFactory.getNetAndIoController();
            44. netAndIoController.outSign = deviceService.findOutSignByDeviceId(expiredKey);
            45. netAndIoController.serverPort = deviceService.findHostPortByDeviceId(expiredKey);
            46. netAndIoController.TcpConnection();
            47. netAndIoController.sendDownControllerMsg();
            48. /**由于订单过期,现在关闭端口电源通断*/
            49. netAndIoController.shutClient();
            50. /**由于数据库里记录的电源还开着,所以我们需要将数据库表中的电源关掉**/
            51. boolean downDevicePowerByDeviceId = deviceService.downDevicePowerByDeviceId(expiredKey);
            52. if (!downDevicePowerByDeviceId)
            53. throw new Exception("数据库power更改异常");
            54. }
            55. if (!updateExOrder) {
            56. throw new Exception("订单过期处理失败");
            57. }
            58. } catch (Exception e) {
            59. System.out.println("---------处理过期订单业务失效---------");
            60. }
            61. System.out.println(expiredKey + "订单过期--------------------");
            62. }
            63. }

            继电器控制类(实现电源的通断)

            1. package com.hlc.utils;/*
            2. User: 黄林春
            3. Date: 2022/7/18
            4. Time: 周一
            5. Project_Name: springDemo712
            6. */
            7. import java.io.*;
            8. import java.net.*;
            9. /***
            10. * 控制继电器吸合辅助工具类
            11. */
            12. public class NetAndIoController {
            13. /*读写缓冲区*/
            14. private BufferedReader reader;
            15. private BufferedWriter writer;
            16. private Socket client;
            17. private ServerSocket server;
            18. /*控制电源输出端口号*/
            19. public int outSign;
            20. /*控制主机端口号:0~65535 去掉主要的计算机运行接口 */
            21. public int serverPort;
            22. public void TcpConnection(){
            23. try{
            24. /*主机所使用的端口,需要在硬件配置里设置好主机的目的IP与端口号*/
            25. server = new ServerSocket(serverPort);
            26. /*连接服务*/
            27. client = server.accept();
            28. System.out.println("连接成功");
            29. String clientAddress = client.getRemoteSocketAddress().toString().substring(1);
            30. String[] clientAddresses = clientAddress.split(":");
            31. System.out.println("客户端IP"+clientAddresses[0]+"端口"+clientAddresses[1]);
            32. reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            33. writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
            34. }catch (IOException e) {
            35. // e.printStackTrace();
            36. System.out.println("----------------------目前的TCP链接并没有断开,依旧使用旧链接-------------------------");
            37. }
            38. }
            39. /*这里的输出口号outSign决定我们去控制那个口的常开吸合*/
            40. public void sendOpenControllerMsg(){
            41. System.out.println("控制继电器通道常开吸合发送:AT+STACHn=1\\r\\n");
            42. String msg = "AT+STACH"+outSign+"=1\r\n";
            43. try {
            44. /*发送数据(主机输出信息口等于继电器的网口输入口)*/
            45. System.out.println("主机发送控制常开指令"+msg);
            46. writer.write(msg);
            47. writer.flush();
            48. /*读数据(继电器收到指令会做出应答,如果应答OK就是执行正常)*/
            49. msg = reader.readLine();
            50. msg = msg.replace("\r\n","\\r\\n");
            51. System.out.println("网络继电器应答"+msg);
            52. } catch (IOException e) {
            53. e.printStackTrace();
            54. }
            55. }
            56. /*这里的输出口号决定我们控制那个口的常关吸合*/
            57. public void sendDownControllerMsg(){
            58. System.out.println("控制继电器通道常关吸合发送:AT+STACHn=0\\r\\n");
            59. String msg = "AT+STACH"+outSign+"=0\r\n";
            60. try{
            61. System.out.println("主机发送控制常开指令"+msg);
            62. writer.write(msg);
            63. writer.flush();
            64. msg = reader.readLine();
            65. msg = msg.replace("\r\n","\\r\\n");
            66. System.out.println("网络继电器应答"+msg);
            67. }catch (Exception e){
            68. e.printStackTrace();
            69. }
            70. }
            71. /*控制开关限时吸合*/
            72. public void sendDelayOpenControllerMsg(){
            73. System.out.println("控制继电器通道开启后延时关闭发送:AT+STACHn=3,10\\r\\n");
            74. String msg = "AT+STACH"+outSign+"=3,10\r\n";
            75. try{
            76. System.out.println("主机发送控制常开指令"+msg);
            77. writer.write(msg);
            78. writer.flush();
            79. msg = reader.readLine();
            80. msg = msg.replace("\r\n","\\r\\n");
            81. System.out.println("网络继电器应答"+msg);
            82. }catch (Exception e){
            83. e.printStackTrace();
            84. }
            85. }
            86. public void shutClient(){
            87. try{
            88. System.out.println("关闭客户端连接");
            89. if (reader != null)
            90. reader.close();
            91. if (writer != null)
            92. writer.close();
            93. if (client != null)
            94. client.close();
            95. if (server != null)
            96. server.close();
            97. } catch (IOException e) {
            98. e.printStackTrace();
            99. }
            100. }
            101. }

            神生成控制继电器类的创建工厂,单例模式,避免浪费

            1. package com.hlc.utils;/*
            2. User: 黄林春
            3. Date: 2022/7/18
            4. Time: 周一
            5. Project_Name: springDemo712
            6. */
            7. import org.springframework.stereotype.Component;
            8. /**
            9. * 代理生成控制继电器类的实例化工厂
            10. */
            11. @Component
            12. public class NetFactory {
            13. private NetAndIoController netAndIoController = null;
            14. public NetAndIoController getNetAndIoController(){
            15. if (netAndIoController == null){
            16. synchronized (NetFactory.class){
            17. if (netAndIoController == null){
            18. netAndIoController = new NetAndIoController();
            19. return netAndIoController;
            20. }
            21. return netAndIoController;
            22. }
            23. }
            24. return netAndIoController;
            25. }
            26. }

            前端微信小程序代码,需要的私聊!

          113. 相关阅读:
            Golang使用自定义IP请求https
            1.DApp-做一个DApp需要学习什么
            redis 分布式锁
            简单工厂和工厂模式
            MongoDB(一):CentOS7离线安装MongoDB单机版与简单使用
            33.3.3 配置HAProxy高可用性
            Abbexa丨Abbexa PCR超级混合液使用说明和相关研究
            自动驾驶的法律和伦理问题
            Sentinel原理分析
            1010hw
          114. 原文地址:https://blog.csdn.net/m0_59588838/article/details/125987374