SpringBoot和Vue实现动态二维码

前言

二维码在现代社交和营销活动中被广泛使用。我们可以在各种渠道上看到二维码的身影,如微信,支付宝,以及其他应用程序中。在本篇博客中,我们将使用SpringBoot和Vue框架来演示如何创建一个能够自动生成并定期刷新的动态二维码。

技术方案

我们会使用以下技术和框架实现这个案例:

  • Spring Boot,用于后端服务端开发
  • VueJS和Element UI,用于前端UI以及与后端的交互
  • QRCode,使用开源库生成动态二维码
  • WebSocket,实现实时推送更新动态二维码

实现

1. 初始化项目

使用Spring Initializr(https://start.spring.io/)初始化一个Spring Boot项目,加入以下的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
    <groupId>net.glxn</groupId>
    <artifactId>qrgen</artifactId>
    <version>1.4.1</version>
</dependency>

2. 实现服务端

在服务端我们会创建一个WebSocket连接,用来实时推送动态二维码。我们创建一个QRCodeService类,实现动态二维码的生成和数据推送逻辑。

首先在QRCodeService里面定义一个WebSocketTemplate,用来向客户端推送消息。

@Service
public class QRCodeService {
    
    
    @Autowired
    private SimpMessagingTemplate template;

    // ...
}

接下来定义生成动态二维码的方法。

public static BufferedImage generateQRImage(String text) throws Exception {
    
    
    ByteArrayOutputStream out = QRCode.from(text).to(ImageType.PNG).stream();
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    return ImageIO.read(in);
}

上述方法使用QRCode库生成二维码,并将结果作为BufferedImage返回。

接下来是实现使用WebSocket发送消息的方法。

@Scheduled(fixedRateString = "${frequency}")
public void generateQRCode() throws Exception {
    
    
    String message = LocalDateTime.now().toString();
    BufferedImage qrImage = generateQRImage(message);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ImageIO.write(qrImage, "png", outputStream);
    byte[] bytes = Base64.encodeBase64(outputStream.toByteArray());

    template.convertAndSend("/topic/qrCode", new String(bytes));
}

这个方法会定期生成一个新的二维码,并使用Base64编码转换为字符串,然后使用WebSocket将其推送到客户端。

使用@Scheduled注解可以设置定时任务,在这里我们可以设置fixedRate参数来指定生成二维码的频率。这个参数可以从application.properties文件中读取。

现在,服务端的代码已经完成了。

3. 实现客户端

我们将使用Vue作为我们的前端框架。使用Vue-Cli命令行工具初始化一个新的Vue项目。

打开App.vue,在template部分定义一个div元素用于展示动态二维码。

<template>
  <div id="app">
    <el-card v-if="qrcodeUrl" class="box-card">
        <div style="text-align: center;">
          <img v-bind:src="qrcodeUrl" height="40%"/>
        </div>
    </el-card>
  </div>
</template>

我们使用Element UI组件库中的card组件来布局界面。qrcodeUrl是用来显示动态二维码的URL地址。

在App.vue中还需要定义一下我们的WebSocket连接代码。

<script>
export default {
      
      
  name: 'App',
  data() {
      
      
    return {
      
      
      qrcodeUrl: null
    }
  },
  mounted() {
      
      
    const url = 'ws://localhost:8080/ws/qrCode';
    this.socket = new WebSocket(url);
    this.socket.onmessage = (event) => {
      
      
      const imageData = event.data;
      const imageUrl = 'data:image/png;base64,' + imageData;
      this.qrcodeUrl = imageUrl;
    };
  }
}
</script>

上述代码会在组件挂载后创建一个WebSocket连接,它通过url连接到服务器端的webSocket中心。当接收到服务端发送的消息,客户端会将收到的图片数据解码,将解码后的data URL赋值给qrcodeUrl。

接下来定义一个生成二维码的方法,用于向服务端发送请求来生成新的动态二维码。

<template>
  <!-- ... -->
  <el-button @click="generateQRCode()">生成</el-button>
  <!-- ... -->
</template>

<script>
export default {
      
      
  // ...
  methods: {
      
      
    generateQRCode() {
      
      
      this.$axios.get('/generateQRCode').then(response => {
      
      
        console.log(response);
      }).catch(error => {
      
      
        console.log(error);
      })
    }
  }
}
</script>

上述代码我们在Vue中定义了一个方法,它向服务端发送一个请求,从而生成新的二维码。我们使用axios库来发送HTTP请求。

4. 编写服务端的WebSocket配置类

为了让服务端支持WebSocket,我们需要定义配置类WebSocketConfig,用来注册WebSocketEndpoint和WebSocketMessageBroker。在这个类中我们还要定义启用WebSocket的CORS配置。

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    
    
 
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
    
    
        registry.addEndpoint("/ws").withSockJS();
    }
 
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
    
    
        registry.enableSimpleBroker("/topic");
        registry.setApplicationDestinationPrefixes("/app");
    }
 
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST")
                .allowCredentials(false).maxAge(3600);
    }
}

现在我们已经完成了后端服务的配置,接下来需要调整一下前端代码。

5. 配置前端的axios

在Vue项目的main.js文件中引入axios,并将其挂载到Vue实例上。

import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'
import 'element-ui/lib/theme-chalk/index.css'
import ElementUI from 'element-ui'

Vue.config.productionTip = false
Vue.use(ElementUI)

axios.defaults.baseURL = 'http://localhost:8080'
Vue.prototype.$axios = axios

new Vue({
    
    
  render: h => h(App),
}).$mount('#app')

在除了修改默认的baseURL之外,上述代码中还配置了Element UI组件库。

我们在浏览器运行这个项目,当用户点击"生成"按钮时,新的二维码会被随机生成。按照上面定义的定时任务,每次生成的二维码会在1分钟后更新。

总结

在本文中,我们学习了如何使用Spring Boot和VueJS框架生成动态二维码。我们使用了QRCode库和WebSocket来实现这个功能,并使用axios进行了前端和后端之间的通信。我希望这篇教程对您有所帮助。

猜你喜欢

转载自blog.csdn.net/weixin_65950231/article/details/130891720