2024-09-04



import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.io.*;
 
public class ExcelWriter {
    private static final int MAX_ROWS = 1000; // 每写完1000行Flush一次
 
    public static void main(String[] args) throws IOException {
        Workbook workbook = new SXSSFWorkbook(); // 创建工作簿实例
        Sheet sheet = workbook.createSheet("数据"); // 创建工作表
 
        // 写入数据
        for (int rowNum = 0; rowNum < 10000; rowNum++) {
            Row row = sheet.createRow(rowNum);
            for (int colNum = 0; colNum < 10; colNum++) {
                Cell cell = row.createCell(colNum);
                cell.setCellValue("Cell " + rowNum + "," + colNum);
            }
            if (rowNum % MAX_ROWS == 0) {
                workbook.write(flushToDisk(workbook)); // 达到指定行数时,将内容flush到磁盘
            }
        }
 
        // 全部数据写入后,关闭工作簿
        workbook.write(flushToDisk(workbook));
        workbook.close();
    }
 
    private static OutputStream flushToDisk(Workbook workbook) throws IOException {
        String filePath = "大数据.xlsx";
        File file = new File(filePath);
        if (!file.exists()) {
            file.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(filePath);
        workbook.write(fos);
        fos.flush();
        return fos;
    }
}

这段代码使用了Apache POI库中的SXSSFWorkbook类来创建一个Excel工作簿,并通过循环写入了大量数据。每写完1000行数据后,会将当前的工作簿状态flush到磁盘中,以防止内存溢出。最后,在所有数据写入完毕后关闭工作簿并释放资源。这是一个实际应用中用于处理大量数据导出的高效方法。

2024-09-04

要搭建一个基本的Spring Cloud Alibaba项目,你需要遵循以下步骤:

  1. 创建一个Spring Boot项目,并添加Spring Cloud Alibaba依赖。
  2. 配置必要的Alibaba Sdk客户端,如Nacos作为服务注册中心和配置中心。
  3. 使用Spring Cloud的注解,如@EnableDiscoveryClient@RefreshScope来启用服务发现和配置管理。

以下是一个简单的示例:

  1. pom.xml中添加Spring Cloud Alibaba依赖(请确保使用正确的Spring Boot和Spring Cloud版本):



<dependencies>
    <!-- Spring Cloud Alibaba dependencies -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
</dependencies>
  1. application.propertiesapplication.yml中配置Nacos服务器地址和应用名:



spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848 # Nacos服务器地址
      config:
        server-addr: 127.0.0.1:8848 # Nacos服务器地址
        file-extension: yaml # 配置文件后缀名
  1. 启动类上添加@EnableDiscoveryClient注解来启用服务注册:



import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
 
@SpringBootApplication
@EnableDiscoveryClient
public class AlibabaApplication {
    public static void main(String[] args) {
        SpringApplication.run(AlibabaApplication.class, args);
    }
}
  1. 配置类或者业务类中使用@Value注解获取配置:



import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
 
@Component
@RefreshScope
public class ConfigProperties {
    @Value("${my.config}")
    private String myConfig;
 
    public String getMyConfig() {
        return myConfig;
    }
}

以上是一个基本的Spring Cloud Alibaba项目的架构。在实际应用中,你可能需要添加更多的配置和代码来满足具体的业务需求。

2024-09-04

在进行MySQL、Redis和Tomcat软件包升级时,通常遵循以下步骤:

  1. 备份:确保在升级前对所有重要数据进行备份。
  2. 检查兼容性:查看新版本的发行说明,确认是否有与其他软件包的兼容性问题。
  3. 停服:在升级之前,确保停止所有相关服务,避免在升级过程中对用户造成影响。
  4. 下载新软件包:从官方网站或可信来源下载新的软件包。
  5. 安装/升级:使用适当的命令安装新软件包或升级现有软件包。
  6. 重新启动服务:安装或升级完成后,重新启动服务。
  7. 测试:确保应用程序能正常运行,并且所有功能都能正常工作。

以下是针对MySQL、Redis和Tomcat的升级命令示例:

MySQL升级(以Linux为例):




# 停止MySQL服务
sudo systemctl stop mysqld
 
# 升级MySQL
sudo yum update mysql
 
# 启动MySQL服务
sudo systemctl start mysqld

Redis升级(以Linux为例):




# 停止Redis服务
sudo systemctl stop redis
 
# 升级Redis
sudo yum update redis
 
# 启动Redis服务
sudo systemctl start redis

Tomcat升级(以Linux为例):




# 停止Tomcat服务
sudo systemctl stop tomcat
 
# 升级Tomcat
# 通常需要下载新版本的Tomcat压缩包,然后解压到指定目录并重命名为新版本号
# 配置Tomcat服务指向新的安装目录
 
# 启动Tomcat服务
sudo systemctl start tomcat

请根据您的操作系统和环境具体调整命令。在执行任何升级操作之前,请确保已经阅读了相关软件的官方升级文档。

2024-09-04

创建一个2048小游戏的大概步骤如下:

  1. 使用SpringBoot创建后端API。
  2. 使用Vue.js创建前端界面。
  3. 前端通过API与后端通信。
  4. 实现游戏逻辑。

后端API(SpringBoot):




@RestController
@RequestMapping("/api/2048")
public class GameController {
 
    private GameService gameService;
 
    @Autowired
    public GameController(GameService gameService) {
        this.gameService = gameService;
    }
 
    @PostMapping("/move")
    public ResponseEntity<?> makeMove(@RequestBody Move move, @RequestHeader("Token") String token) {
        // 调用GameService来执行移动
        Game game = gameService.makeMove(move, token);
        return ResponseEntity.ok(game);
    }
 
    @GetMapping("/{token}")
    public ResponseEntity<?> getGameState(@PathVariable("token") String token) {
        // 获取游戏状态
        Game game = gameService.getGameState(token);
        return ResponseEntity.ok(game);
    }
}

前端(Vue.js):




<template>
  <div id="app">
    <game-board :tiles="tiles"></game-board>
    <button @click="makeMove('up')">Up</button>
    <button @click="makeMove('down')">Down</button>
    <button @click="makeMove('left')">Left</button>
    <button @click="makeMove('right')">Right</button>
  </div>
</template>
 
<script>
import GameBoard from './components/GameBoard.vue';
 
export default {
  components: {
    GameBoard
  },
  data() {
    return {
      tiles: [],
      token: ''
    };
  },
  created() {
    this.fetchGameState();
  },
  methods: {
    fetchGameState() {
      // 假设已经有token
      this.axios.get('/api/2048/' + this.token)
        .then(response => {
          this.tiles = response.data.tiles;
        });
    },
    makeMove(direction) {
      this.axios.post('/api/2048/move', { direction, token: this.token })
        .then(response => {
          this.tiles = response.data.tiles;
        });
    }
  }
};
</script>

这只是一个简单的框架,你需要实现GameService、GameBoard组件和其他相关的类和方法。这个例子假设你已经有了SpringBoot和Vue.js的基础知识,并且配置好了SpringBoot后端API和Vue.js项目。

注意:这个例子没有实现游戏的实际逻辑,只是展示了如何使用SpringBoot和Vue.js创建一个API和一个简单的前端界面。实际的游戏逻辑需要在GameService中实现,比如生成新的数字块、移动块、检测是否有可用的移动、判断游戏是否结束等。

2024-09-04

在PostgreSQL中,数组类型是一种强大的数据类型,它允许存储一系列相同类型的值。数组可以通过使用方括号 [] 进行声明,元素之间使用逗号 , 分隔。

以下是一些使用数组类型的示例:

  1. 创建包含数组类型列的表:



CREATE TABLE example_table (
    id SERIAL PRIMARY KEY,
    numbers INTEGER[],
    names TEXT[]
);
  1. 向表中插入数组数据:



INSERT INTO example_table (numbers, names) VALUES ('{1,2,3}', '{"Alice", "Bob"}');
  1. 查询数组列中的数据:



SELECT numbers, names FROM example_table;
  1. 更新数组列中的数据:



UPDATE example_table SET numbers = '{4,5,6}' WHERE id = 1;
  1. 使用数组的索引和切片:



-- 获取第一个名字
SELECT names[1] FROM example_table;
 
-- 获取前两个数字
SELECT numbers[:2] FROM example_table;
 
-- 用新数组替换前两个数字
UPDATE example_table SET numbers[1:2] = '{10,11}' WHERE id = 1;
  1. 使用数组的函数和操作符,如 && 用于数组之间的交集,|| 用于数组合并:



-- 查找名字包含 "Bob" 和 "Alice" 的行
SELECT * FROM example_table WHERE names && '{Alice,Bob}';
 
-- 将每行的名字和给定数组合并
SELECT names || '{Charlie}' FROM example_table;
  1. 使用 UNNEST 函数将数组展开成一系列的行:



SELECT id, numbers
FROM example_table, UNNEST(numbers) as num;

数组在处理大量数据和需要高效查询的场景中非常有用,但也需要注意数组操作可能在性能上有显著差异,尤其是在数组较大或者在大量数组操作的情况下。

2024-09-04

移植Ubuntu 20.04.4根文件系统到Firefly RK3399开发板的步骤大致如下:

  1. 准备工作:

    • 获取Ubuntu 20.04.4镜像。
    • 确保你有适合RK3399的U-Boot和内核。
    • 制作一个启动介质,比如SD卡或者EMMC。
  2. 制作启动介质:

    • 将U-Boot、内核、Ubuntu镜像以及必要的文件放入SD卡或EMMC。
  3. 配置U-Boot:

    • 根据你的硬件配置U-Boot环境变量,比如设备分区和启动参数。
  4. 烧录并启动系统:

    • 将启动介质插入开发板,上电启动。
  5. 安装Ubuntu系统:

    • 系统启动后,根据屏幕上的指示进行安装。
  6. 配置系统:

    • 安装必要的驱动和软件包。
    • 配置网络和其他系统设置。
  7. 制作根文件系统:

    • 使用debootstrapapt-clone等工具制作一个基本的文件系统。
  8. 定制根文件系统:

    • 根据需要添加或删除软件包。
  9. 重新编译内核(如果需要):

    • 为你的硬件添加必要的驱动和内核模块。
  10. 更新启动介质:

    • 将定制的根文件系统和内核更新到启动介质中。
  11. 重新启动并验证系统:

    • 确保所有配置正确,系统能够从新的根文件系统启动。

以下是一个简化的示例步骤:




# 准备工作:获取Ubuntu镜像和适合RK3399的U-Boot、内核
 
# 制作启动介质(例如使用SD卡)
sudo dd if=u-boot.img of=/dev/sdx bs=1M
sudo dd if=kernel.img of=/dev/sdx bs=1M seek=1
sudo dd if=ubuntu-rootfs.tar.gz of=/dev/sdx bs=1M seek=100
 
# 连接启动介质到开发板,并上电启动
 
# 安装Ubuntu,配置网络等
 
# 制作定制的根文件系统
sudo debootstrap --arch=arm64 focal /mnt/myroot http://archive.ubuntu.com/ubuntu
 
# 进行定制,比如添加软件包
sudo apt-get -arch=arm64 install --reinstall -y --root=/mnt/myroot ...
 
# 更新启动介质(更新根文件系统和内核映像)
sudo dd if=/mnt/myroot of=/dev/sdx bs=1M
 
# 重新启动开发板并验证系统

注意:上述代码是示例,实际操作时需要根据你的硬件和系统环境进行相应的调整。

2024-09-04



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.server.authorization.RedisOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenSerializer;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenSerializerFactory;
 
@Configuration
public class RedisTokenConfig {
 
    @Bean
    public RedisOAuth2AuthorizationService redisOAuth2AuthorizationService(RedisConnectionFactory redisConnectionFactory) {
        return new RedisOAuth2AuthorizationService(redisConnectionFactory);
    }
 
    @Bean
    public OAuth2TokenSerializer<OAuth2TokenCustomizer> oAuth2TokenSerializer(RedisConnectionFactory redisConnectionFactory) {
        OAuth2TokenSerializerFactory factory = new OAuth2TokenSerializerFactory();
        factory.setRedisConnectionFactory(redisConnectionFactory);
        return factory.createSerializer();
    }
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

这个配置类定义了Redis存储的相关Bean,包括RedisOAuth2AuthorizationService用于存储授权信息,OAuth2TokenSerializer用于序列化和反序列化令牌,以及基本的RedisTemplate用于与Redis交互。这些Bean可以被注入到OAuth2AuthorizationServerConfiguration中,以确保授权服务器使用Redis作为令牌存储。

2024-09-04



-- 假设我们有一个名为 'example_table' 的表,它有一个 'bytea' 类型的字段 'data_field'
-- 我们可以使用以下 SQL 语句来插入和检索 'bytea' 类型的数据
 
-- 插入数据
INSERT INTO example_table (data_field) VALUES ('\x0001020304');
 
-- 检索数据
SELECT data_field FROM example_table;
 
-- 更新数据
UPDATE example_table SET data_field = '\x05060708' WHERE condition;
 
-- 删除数据
DELETE FROM example_table WHERE condition;

在这个例子中,我们演示了如何使用 PostgreSQL 的 bytea 数据类型进行插入、检索、更新和删除操作。注意,在实际应用中,你需要根据你的具体需求来定制查询条件(WHERE 子句中的 condition)。

2024-09-04

在Spring Boot中加速单元测试的执行速度可以采取以下几种策略:

  1. 使用Spring Boot的测试注解@ActiveProfiles("test")来启用一个快速的测试配置。
  2. 使用@DirtiesContext注解来避免在每个测试之后重新加载应用程序上下文。
  3. 使用JUnit的@RepeatedTest@ParameterizedTest注解来减少重复的测试代码。
  4. 对于数据库操作,可以使用Spring Boot的@DataJpaTest注解来仅加载JPA测试支持,并且可以指定使用内存数据库。
  5. 对于非JPA测试,可以使用@WebAppConfiguration来禁用Web环境的初始化,或者使用@MockMvc来进行REST API测试。
  6. 使用JUnit的Assume类来跳过某些测试,如果不满足某些前提条件。
  7. 使用JUnit的ExpectedException规则来避免使用try-catch

以下是一个简单的示例,展示如何使用@ActiveProfiles来加速测试执行:




@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test") // 启用快速测试配置
public class MyServiceTest {
 
    @Autowired
    private MyService myService;
 
    @Test
    public void testMyService() {
        // 编写测试用例
    }
}

在实际应用中,选择适合的策略以达到最佳测试执行速度。

2024-09-04

Spring Boot和Spring Cloud版本兼容性是一个重要的考量因素。以下是一些常见的Spring Boot和Spring Cloud版本对应关系的示例:

Spring Boot 2.7.x 兼容 Spring Cloud 2021.0.x 及更早版本

Spring Boot 2.6.x 兼容 Spring Cloud 2020.0.x 及更早版本

Spring Boot 2.5.x 兼容 Spring Cloud 2020.0.x 及更早版本

Spring Boot 2.4.x 兼容 Spring Cloud 2020.0.x 及更早版本

Spring Boot 2.3.x 兼容 Spring Cloud Greenwich 及更早版本

Spring Boot 2.2.x 兼容 Spring Cloud Hoxton 及更早版本

Spring Boot 2.1.x 兼容 Spring Cloud Finchley 及更早版本

在实际开发中,你需要根据自己的需求选择合适的Spring Boot和Spring Cloud版本。如果你需要使用特定的Spring Boot版本,你可以查看Spring官方文档找到对应的Spring Cloud版本。

例如,如果你决定使用Spring Boot 2.5.x,你可以查看Spring Boot 2.5.x的官方文档,它会列出所有与之兼容的Spring Cloud版本。

在项目的pom.xml中,你可以这样配置版本:




<!-- Spring Boot 2.5.x -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.x</version>
    <relativePath/>
</parent>
 
<!-- Spring Cloud 2020.0.x 对应的依赖管理 -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>2020.0.x</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

请注意,你应该替换2.5.x2020.0.x为你选择的Spring Boot和Spring Cloud的实际版本号。