2025/9/22

vue3 runtime

如果要使用 vue3 runtime,也就是 vue.runtime.esm-browser.js,而不使用 vue.esm-browser.js。這兩個版本的差異是使用後者,有支援 template,可直接將 template 字串寫在 component 裡面,但如果使用 runtime library,因為這個檔案大小比較小,缺少了動態編譯 template 的功能,必須改寫為使用 render function。

實例

以下是可以直接在 browser 執行的範例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<div id="app"></div>

<script type="importmap">
    {
        "imports": {
            "vue": "https://unpkg.com/vue@3.5.13/dist/vue.runtime.esm-browser.js",
            "vue-i18n": "https://unpkg.com/vue-i18n@11.1.1/dist/vue-i18n.runtime.esm-browser.js"
        }
    }
</script>

<script type="module">
    import { createApp, h } from 'vue';
    import { createI18n, useI18n } from 'vue-i18n';

    const messages = {
        en: { greeting: 'Hello!' },
        zh: { greeting: '你好!' }
    };

    const i18n = createI18n({
        legacy: false,
        locale: 'en',
        messages
    });

    const App = {
        setup() {
            const { t, locale } = useI18n(); // 正確取得 t() 函數

            const toggleLang = () => {
                locale.value = locale.value === 'en' ? 'zh' : 'en';
            };

            return () =>
                h('div', [
                    h('h1', t('greeting')),
                    h('button', { onClick: toggleLang }, '🌐 Switch Language')
                ]);
        }
    };

    createApp(App).use(i18n).mount('#app');
</script>
</body>
</html>

compiler-dom

vue3 官方提供了一個 compiler-dom,可以將 template 字串轉換為 render function。

安裝首先要安裝 compiler-dom

npm i @vue/compiler-dom

撰寫一個 convert.js

// https://www.npmjs.com/package/@vue/compiler-dom
// npm i @vue/compiler-dom

const fs = require('fs');
const path = require('path');
const { compile } = require('@vue/compiler-dom');

const file = process.argv[2];

if (!file || !file.endsWith('.template.html')) {
  console.error('請提供一個 .template html 檔案,例如:node convert.js MyComponent.html');
  process.exit(1);
}

const filePath = path.resolve(process.cwd(), file);

const template = fs.readFileSync(filePath, 'utf-8');

// 編譯 template 成 render 函數
const { code } = compile(template, {
  mode: 'module',
  prefixIdentifiers: true, // 避免 with()
  filename: file
});

// 產出 JS 檔案名稱
const baseName = path.basename(file, '.template.html');
const outputFile = `${baseName}.template.render.js`;

// // 包裝為可匯入的模組
const outputContent = `
${code}
`;
// 寫入檔案
fs.writeFileSync(outputFile, outputContent.trim());

console.log(`Render function 已輸出為:${outputFile}`);

使用方法

把 template 的部分,改為獨立的 test.template.html 檔案

<div>
    <h1> {{ t("greeting") }} </h1>
    <button @click="toggleLang()">🌐 Switch Language</button>
</div>

透過 nodejs 將 template 轉換為 render function

import { toDisplayString as _toDisplayString, createElementVNode as _createElementVNode, openBlock as _openBlock, createElementBlock as _createElementBlock } from "vue"

export function render(_ctx, _cache) {
  return (_openBlock(), _createElementBlock("div", null, [
    _createElementVNode("h1", null, _toDisplayString(_ctx.$t("greeting")), 1 /* TEXT */),
    _createElementVNode("button", {
      onClick: $event => (_ctx.toggleLang())
    }, "🌐 Switch Language", 8 /* PROPS */, ["onClick"])
  ]))
}

改寫原本的測試網頁

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<div id="app"></div>

<script type="importmap">
    {
        "imports": {
            "vue": "https://unpkg.com/vue@3.5.13/dist/vue.runtime.esm-browser.js",
            "vue-i18n": "https://unpkg.com/vue-i18n@11.1.1/dist/vue-i18n.runtime.esm-browser.js",

            "render": "./test.template.render.js"
        }
    }
</script>

<script type="module">
    import { createApp, h } from 'vue';
    import { createI18n, useI18n } from 'vue-i18n';
    import {render} from 'render';

    const renderFn = render;

    const i18n = createI18n({
        legacy: false,
        locale: 'en',
        fallbackLocale: "en",
        messageCompiler: null,
        messages: {
            "en": {
                "greeting": 'Hello!'
            },
            "zh": {
                "greeting": '你好!'
            },
        },
    });

    const App = {
        setup() {
            const { t, locale } = useI18n();

            const toggleLang = () => {
                locale.value = locale.value === 'en' ? 'zh' : 'en';
            };

            return {
                t, locale, toggleLang
            };
        },
        render: renderFn,
        methods: {
        }
    };

    createApp(App).use(i18n).mount('#app');
</script>
</body>
</html>

note

點擊切換語言時,網頁 console 會出現這樣的警告訊息

[intlify] the message that is resolve with key 'greeting' is not supported for jit compilation

不影響網頁操作,但還不知道為什麼會出現這個 warning

2025/9/15

Container vs VM

Container 是類似 docker 這樣建構在某個 OS 的虛擬機器,VM 是類似 Hypervisor VMWare 建立的虛擬機器。

VM

優點:

  • 從硬體開始就虛擬化,機器獨立

  • 可在不同 VM 安裝不同的 OS

  • 不同應用程式內的相關套件耦合,不會互相影響

  • 適合比較大型,需要很多不同的整合服務的應用

缺點:

  • 耗用的硬碟空間較多,使用的硬體資源比較高

  • 啟動服務需要比較長的時間

Container

優點:

  • 檔案比較小

  • 啟動速度快

  • 耗用系統資源比較少

  • 容易更新

  • 通常以應用程式為單位

缺點:

  • 主要依賴 Host OS的操作,無法同時安裝不同的 OS

  • container 之間的元件部署比較複雜

2025/9/8

Open Street Map Local Server

Switch2OSM

https://switch2osm.org/

因為 Open Street Map 的免費公用特性,所以我們可以複製這些地圖資料到自己的地圖 server,Switch2OSM 是一個推廣 OSM 的專案,我們可以透過這個專案,建置自己的 Map Server

PBF format

.pbf空間數據詳解

PBF 就是 Protocolbuffer Binary Format 這是基於 ProtoBuffer 的一種 binary data format,這是一種比 XML, GeoJSON 等等地圖格式還要精簡的檔案格式。

在 OSM 通常是以 *.osm.pbf 這個 file extension 代表 OSM PBF file

Open Street Map 在 PBF Format - OpenStreetMap Wiki 有說明該檔案格式的定義。

Taiwan OSM

Geofabrik Download Server Taiwan 這個網站,有固定更新從 Open Street Map 下載的 Taiwan 離線地圖,我們可以到這個網站下載 taiwan-latest.osm.pbf

取得 osm PBF 檔案以後,就可以匯入 switch2osm local map server

docker

參考 Using a Docker container – Switch2OSM 的說明,最簡單的方式就是透過 container 建置 switch2osm

以下以 Redhat 系列的 podman 進行測試

匯入 osm.pbf 檔案

podman volume create osm-data

podman run  --name osmtile-import -v /root/download/osm/taiwan-latest.osm.pbf:/data/region.osm.pbf  -v osm-data:/data/database/  overv/openstreetmap-tile-server  import

tile server

podman volume create osm-tiles
# 啟動 tile server
podman run --name osmtile -p 8081:80 -v osm-data:/data/database/ -v osm-tiles:/data/tiles -d overv/openstreetmap-tile-server run

啟動後就可以在 http://localhost:8081/tile/ 看到透過 Leaflet 取得的 OSM 地圖

2025/9/1

WhisperSpeech

WhisperSpeech是一種反轉Whisper技術,實做的TTS系統。

安裝測試

在 Rocky Linux 8 的 Python 3.11 安裝測試

dnf install python3.11
# 在執行測試時,會需要 python.h,故需要安裝 devel 套件
dnf install python3.11-devel

python3 -m venv /root/venv/whisperspeech
source /root/venv/whisperspeech/bin/activate

pip3 install WhisperSpeech
pip3 install webdataset

測試程式

import torch
import torch.nn.functional as F
from whisperspeech.pipeline import Pipeline

pipe = Pipeline(s2a_ref='collabora/whisperspeech:s2a-q4-tiny-en+pl.model', torch_compile=True)
pipe.generate_to_file("output.wav", "Hello from WhisperSpeech.")

以 time 測試執行時間

time python3 test.py
real    0m38.452s
user    2m19.176s
sys    0m1.683s

真實時間大約花了 40s,這邊是用 Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz 的機器,沒有用到 GPU

這個網站可以聽到 WhisperSpeech 產生的語音結果

WhisperSpeech - New Text-To-Speech Model In Town

References

GitHub - WhisperSpeech/WhisperSpeech: An Open Source text-to-speech system built by inverting Whisper.

whisperspeech 英文TTS的实现_whisper speech-CSDN博客

2025/8/25

Spring Boot 3 JPA multiple datasource

在一個 Spring Boot 3 project 同時連接到兩個 database,需要用兩個設定檔指定兩個 datasource,分別設定不同的 entityManager, transactonManager, jdbcTemplate。

  • application.yml

    spring:
      application:
        name: project
      jpa:
        properties:
          hibernate:
            # dialect: org.hibernate.dialect.MySQLDialect
            dialect: org.hibernate.community.dialect.MySQLLegacyDialect
    
    project:
      kokods:
        url: jdbc:mariadb://localhost:3306/koko
        username: root
        password: password
        schema: koko
        type: com.zaxxer.hikari.HikariDataSource
        hikari:
          connection-timeout: 30000 # milliseconds that a client will wait for a new connection from the pool  30 seconds
          minimum-idle: 1           # minimum number of idle connections
          maximum-pool-size: 100    # maximum number of connections
          idle-timeout: 600000      # maximum amount of time that a connection may sit idle in the pool of connections  10 mins
          max-lifetime: 1800000     # a connection can be pooled for before being destroyed  30 mins
          auto-commit: true
          connection-test-query: SELECT CURRENT_TIMESTAMP
      db2ds:
        url: jdbc:mariadb://localhost:3306/db2
        username: root
        password: password
        schema: db2
        type: com.zaxxer.hikari.HikariDataSource
        hikari:
          connection-timeout: 30000 # milliseconds that a client will wait for a new connection from the pool  30 seconds
          minimum-idle: 1           # minimum number of idle connections
          maximum-pool-size: 100    # maximum number of connections
          idle-timeout: 600000      # maximum amount of time that a connection may sit idle in the pool of connections  10 mins
          max-lifetime: 1800000     # a connection can be pooled for before being destroyed  30 mins
          auto-commit: true
          connection-test-query: SELECT CURRENT_TIMESTAMP
    
    logging:
      level:
        com.zaxxer.hikari: TRACE
        com.zaxxer.hikari.HikariConfig: DEBUG
  • @Configuration設定

    • KoKoConfig.java

      package tw.com.maxkit.koko.config;
      
      import com.zaxxer.hikari.HikariDataSource;
      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
      import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
      import org.springframework.context.annotation.*;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.boot.context.properties.ConfigurationProperties;
      import org.springframework.boot.jdbc.DataSourceBuilder;
      import org.springframework.core.env.Environment;
      import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
      import org.springframework.jdbc.core.JdbcTemplate;
      import org.springframework.orm.jpa.JpaTransactionManager;
      import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
      import org.springframework.transaction.PlatformTransactionManager;
      import org.springframework.transaction.annotation.EnableTransactionManagement;
      
      import javax.sql.DataSource;
      
      @Configuration
      //@PropertySource({"classpath:persistence-multiple-db.properties"})
      @EnableJpaRepositories(
              basePackages = "tw.com.maxkit.koko.dao.jpa",
              entityManagerFactoryRef = "kokoEntityManagerFactory",
              transactionManagerRef = "kokoTransactionManager"
      )
      @EnableTransactionManagement
      public class KoKoConfig {
          @Autowired
          private Environment env;
      
          @Primary
          @Bean("kokoDataSourceProperties")
          @ConfigurationProperties("project.kokods")
          public DataSourceProperties kokoDataSourceProperties() {
              return new DataSourceProperties();
          }
      
          @Primary
          @Bean("kokoDataSource")
          @Qualifier(value="kokoDataSourceProperties")
          @ConfigurationProperties(prefix = "project.kokods.hikari")
          public HikariDataSource kokoDataSource() {
              return kokoDataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
          }
      
          // 如果不修改 Hikari 的參數,可直接使用這個 datasource,但要注意設定檔 url 要改為 jdbc-url
      //    @Bean("lartelDataSource")
      //    @ConfigurationProperties("lartel.kokods")
      //    public DataSource lartelDataSource() {
      //        return DataSourceBuilder.create().build();
      //    }
      
          @Primary
          @Bean("kokoEntityManagerFactory")
          public LocalContainerEntityManagerFactoryBean kokoEntityManagerFactory(
                  @Qualifier("kokoDataSource") DataSource kokoDataSource,
                  EntityManagerFactoryBuilder builder) {
              return builder //
                      .dataSource(kokoDataSource) //
                      .packages("tw.com.maxkit.koko.data.entity") //
                      .persistenceUnit("kokoDs") //
                      .build();
          }
      
          @Primary
          @Bean("kokoTransactionManager")
          public PlatformTransactionManager kokoTransactionManager(
                  @Qualifier("kokoEntityManagerFactory") LocalContainerEntityManagerFactoryBean kokoEntityManagerFactory) {
              return new JpaTransactionManager(kokoEntityManagerFactory.getObject());
          }
      
          @Primary
          @Bean("kokoJdbcTemplate")
          public JdbcTemplate kokoJdbcTemplate(
                  @Qualifier("kokoDataSource") DataSource kokoDataSource) {
              return new JdbcTemplate(kokoDataSource);
          }
      }
    • Db2Config.java

      package tw.com.maxkit.db2.config;
      
      import com.zaxxer.hikari.HikariDataSource;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
      import org.springframework.boot.context.properties.ConfigurationProperties;
      import org.springframework.boot.jdbc.DataSourceBuilder;
      import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.context.annotation.Primary;
      import org.springframework.core.env.Environment;
      import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
      import org.springframework.jdbc.core.JdbcTemplate;
      import org.springframework.orm.jpa.JpaTransactionManager;
      import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
      import org.springframework.transaction.PlatformTransactionManager;
      import org.springframework.transaction.annotation.EnableTransactionManagement;
      
      import javax.sql.DataSource;
      
      @Configuration
      @EnableJpaRepositories(
              basePackages = "tw.com.maxkit.db2.dao.jpa",
              entityManagerFactoryRef = "lartelEntityManagerFactory",
              transactionManagerRef = "lartelTransactionManager"
      )
      @EnableTransactionManagement
      public class LartelConfig {
          @Autowired
          private Environment env;
      
          // 這兩個 method 會套用修改 Hikari 的參數
          @Bean("db2DataSourceProperties")
          @ConfigurationProperties("project.db2ds")
          public DataSourceProperties db2DataSourceProperties() {
              return new DataSourceProperties();
          }
      
          @Bean("db2DataSource")
          @Qualifier(value="db2DataSourceProperties")
          @ConfigurationProperties(prefix = "project.db2ds.hikari")
          public HikariDataSource db2DataSource() {
              return db2DataSourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();
          }
      
          // 如果不修改 Hikari 的參數,可直接使用這個 datasource,但要注意設定檔 url 要改為 jdbc-url
      //    @Bean("lartelDataSource")
      //    @ConfigurationProperties("lartel.lartelds")
      //    public DataSource lartelDataSource() {
      //        return DataSourceBuilder.create().build();
      //    }
      
          @Bean("db2EntityManagerFactory")
          public LocalContainerEntityManagerFactoryBean db2EntityManagerFactory(
                  @Qualifier("db2DataSource") DataSource db2DataSource,
                  EntityManagerFactoryBuilder builder) {
              return builder //
                      .dataSource(db2DataSource) //
                      .packages("tw.com.maxkit.db2.data.entity") //
                      .persistenceUnit("db2Ds") //
                      .build();
          }
      
          @Bean("db2TransactionManager")
          public PlatformTransactionManager db2TransactionManager(
                  @Qualifier("db2EntityManagerFactory") LocalContainerEntityManagerFactoryBean lartelEntityManagerFactory) {
              return new JpaTransactionManager(db2EntityManagerFactory.getObject());
          }
      
          @Bean("db2JdbcTemplate")
          public JdbcTemplate db2JdbcTemplate(
                  @Qualifier("db2DataSource") DataSource db2DataSource) {
              return new JdbcTemplate(db2DataSource);
          }
      }
  • 第一個 datasource 部分的 DAO,另一個是類似的作法

    package tw.com.maxkit.koko.dao.jpa;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;
    import tw.com.maxkit.koko.data.entity.Uservo;
    
    import java.util.List;
    
    @Repository
    public interface UservoDAO extends JpaRepository<Uservo, Long> {
        public List<Uservo> queryAll();
    }
    • DAO 的 implementation

      package tw.com.maxkit.koko.dao.jpa;
      
      import jakarta.persistence.EntityManager;
      import jakarta.persistence.TypedQuery;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.data.jpa.repository.JpaContext;
      import org.springframework.stereotype.Component;
      import tw.com.maxkit.koko.data.entity.Uservo;
      
      import java.util.List;
      
      @Component
      public class UservoDAOImpl {
          private final EntityManager em;
      
          @Autowired
          public UservoDAOImpl(JpaContext context) {
              this.em = context.getEntityManagerByManagedType(Uservo.class);
          }
      
          public List queryAll() {
              String jpql = "SELECT u FROM Uservo u";
              TypedQuery query = this.em.createQuery(jpql, Uservo.class);
              return query.getResultList();
          }
      }
  • Service

    package tw.com.maxkit.koko.service;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import tw.com.maxkit.koko.dao.jpa.UservoDAO;
    import tw.com.maxkit.koko.data.entity.Uservo;
    
    @Service
    public class UservoService {
    
        @Autowired
        private UservoDAO uservoDAO;
    
        public void findAll() {
            System.out.println("\n使用 Spring Data JPA 衍生方法查詢 uservo 的資料:");
    //        this.uservoRepository.findAll().forEach(System.out::println);
            this.uservoDAO.findAll().forEach(
                    uservo -> System.out.println("uservoseq="+uservo.getUservoseq()+", userid="+uservo.getUserid())
            );
        }
    
        @Transactional("kokoTransactionManager")
        public Uservo testTransactional(String userid, String username) {
            // 刪除全部
    //        this.uservoRepository.deleteAll();
    
            // 寫入一筆
            Uservo a = new Uservo();
            a.setUserid(userid);
            a.setUsername(username);
            a = this.uservoDAO.save(a);
    
            // 故意埋入 RuntimeException: ArrayIndexOutOfBoundsException
            System.out.println(new String[] {}[1]);
    
            return a;
        }
    
        public void queryAll() {
            System.out.println("\n使用 queryAll 查詢 uservo 的資料:");
    //        this.uservoRepository.findAll().forEach(System.out::println);
            this.uservoDAO.queryAll().forEach(
                    uservo -> System.out.println("uservoseq="+uservo.getUservoseq()+", userid="+uservo.getUserid())
            );
        }
    }

References

Spring Boot + Spring Data JPA 配置多個 DataSource

HikariCP 连接池多数据源配置