2024-09-05

Spring Boot 整合 ELK 主要涉及到 Spring Boot 应用的日志收集和传输,以及 ELK (Elasticsearch, Logstash, Kibana) stack 的配置和使用。

  1. 在 Spring Boot 应用中添加 Logback 配置,用于将日志发送到 Logstash。



<!-- logback-spring.xml -->
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml" />
    <property name="LOG_FILE" value="spring-boot-logstash.log" />
 
    <appender name="LOGSTASH" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>tcp:localhost:4560</destination>
        <encoder class="net.logstash.logback.encoder.LogstashEncoder" />
    </appender>
 
    <root level="INFO">
        <appender-ref ref="LOGSTASH" />
    </root>
</configuration>
  1. 在 Logstash 配置中解析 Spring Boot 应用日志。



# logstash.conf
input {
  tcp {
    port => 4560
    codec => json_lines
  }
}
 
filter {
  # 解析 Logback 的 LogstashEncoder 输出的 JSON 格式日志
}
 
output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "spring-boot-%{+YYYY.MM.dd}"
  }
}
  1. 启动 Elasticsearch, Logstash 和 Kibana 服务。



# 启动 Elasticsearch
bin/elasticsearch
 
# 启动 Logstash 并加载配置
bin/logstash -f logstash.conf
 
# 启动 Kibana
bin/kibana
  1. 最后,启动 Spring Boot 应用并生成日志,通过 Logstash 收集并在 Kibana 中查看和搜索。

以上步骤可以将 Spring Boot 应用与 ELK stack 整合,实现日志的收集、分析和可视化。

2024-09-05



import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;
 
@Configuration
public class SessionConfig {
 
    @Bean
    public RedisHttpSessionConfiguration redisHttpSessionConfiguration() {
        RedisHttpSessionConfiguration config = new RedisHttpSessionConfiguration();
        config.setMaxInactiveIntervalInSeconds(1800); // 设置session的失效时间
        return config;
    }
 
    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        serializer.setCookieName("MY_SESSIONID"); // 自定义cookie名称
        serializer.setCookiePath("/"); // 设置全站有效的cookie路径
        serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$"); // 设置cookie的域名
        serializer.setUseHttpOnlyCookie(true); // 设置只能通过http访问
        return serializer;
    }
}

这段代码定义了一个配置类SessionConfig,其中包含了redisHttpSessionConfiguration方法来配置Spring Session使用Redis存储session数据,并设置了session的失效时间。同时,cookieSerializer方法自定义了cookie的名称、路径、域名和是否只能通过HTTP访问等属性。这样,开发者可以通过集中管理session来维护用户的登录状态,并通过cookie来实现用户信息的传递和验证。

2024-09-05



import re
 
def parse_mongodb_log(log_line):
    """
    解析MongoDB日志行并提取关键信息。
    :param log_line: 单行MongoDB日志。
    :return: 包含关键信息的字典。
    """
    # 正则表达式模板,根据实际日志格式进行调整
    pattern = r'^(?P<date>\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})\.\d{3}\s+
<div class="katex-block">\[(?P&lt;level&gt;\w+)\]</div>
\\s+(?P<message>.+)$'
    match = re.match(pattern, log_line)
    if match:
        return match.groupdict()
    return None
 
# 示例使用
log_line = '2023-03-15 12:00:00.123 [INFO] Memory footprint: 500MB'
parsed_log = parse_mongodb_log(log_line)
if parsed_log:
    print(f"日期: {parsed_log['date']}")
    print(f"级别: {parsed_log['level']}")
    print(f"信息: {parsed_log['message']}")
else:
    print("日志解析失败")

这段代码定义了一个函数parse_mongodb_log,它接受一个MongoDB日志行作为输入,使用正则表达式解析日期、级别和信息,并以字典形式返回。如果日志行格式与正则表达式匹配,则返回包含关键信息的字典;否则返回None。代码提供了一个使用示例,展示了如何调用这个函数并处理解析结果。

2024-09-05

要使用Python编写数据库后端,您可以使用sqlite3模块来连接和操作SQLite数据库,或者使用psycopg2mysql-connector-python等模块来连接和操作其他类型的数据库。以下是一个使用sqlite3创建简单后端的例子:




import sqlite3
 
# 连接到SQLite数据库
# 数据库文件是 test.db
# 如果文件不存在,会自动在当前目录创建:
conn = sqlite3.connect('test.db')
 
# 创建一个Cursor:
cursor = conn.cursor()
 
# 执行一条SQL语句,创建user表:
cursor.execute('CREATE TABLE IF NOT EXISTS users (id VARCHAR(20) PRIMARY KEY, name VARCHAR(20))')
 
# 关闭Cursor:
cursor.close()
 
# 提交事务:
conn.commit()
 
# 关闭Connection:
conn.close()

要操作数据库,您可以使用cursor.execute()方法执行SQL语句,并使用cursor.fetchall()cursor.fetchone()等方法获取查询结果。

对于更复杂的后端,您可能需要构建Web服务,如使用Flask或Django框架,并在其中集成数据库操作。这通常涉及到定义路由、数据库模型和视图函数等。

2024-09-05

解释:

Tomcat 在 Linux 环境下出现乱码通常是由于字符编码设置不正确导致的。Tomcat 默认使用 ISO-8859-1 编码,而中文通常使用 UTF-8 编码。

解决方法:

  1. 设置 Tomcat 配置文件:

    • 找到 conf/server.xml 文件。
    • 修改 <Connector> 标签,添加 URIEncoding="UTF-8" 属性,例如:

      
      
      
      <Connector port="8080" protocol="HTTP/1.1"
                connectionTimeout="20000"
                redirectPort="8443"
                URIEncoding="UTF-8" />
    • 重启 Tomcat 使配置生效。
  2. 如果是应用内部出现乱码,检查应用的字符编码设置,确保请求和响应都使用 UTF-8 编码。
  3. 如果是日志文件乱码,需要修改日志配置文件(如 logging.properties),确保日志文件编码设置正确。
  4. 检查系统环境变量,确保 LANG 和其他相关的环境变量设置为支持中文的编码,如 zh_CN.UTF-8
  5. 如果是 JSP 页面乱码,确保页面头部指定了正确的字符编码:

    
    
    
    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  6. 如果是通过外部配置文件造成乱码,确保外部配置文件的编码格式为 UTF-8 无 BOM。
  7. 如果是通过数据库造成乱码,检查数据库连接配置,确保字符集设置正确,如:

    
    
    
    jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8
  8. 如果是通过 HTTP 传递参数造成乱码,确保 HTTP 请求头部的 Content-Type 包含正确的字符编码。

总结,要解决 Tomcat 在 Linux 环境下乱码问题,关键是要确保字符编码设置一致,并且在各个环节中保持一致:包括配置文件、应用程序、日志文件、数据库连接、HTTP 请求等。

2024-09-05

Spring Security 整合 JWT 的示例代码如下:

  1. 添加依赖(以 Maven 为例):



<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>
  1. 配置 Security 和 JWT:



@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
 
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()
            .antMatchers("/authenticate").permitAll()
            .anyRequest().authenticated();
 
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    }
 
    @Bean
    public SecurityEvalContextExtension securityEvalContextExtension() {
        return new SecurityEvalContextExtension();
    }
}
  1. 实现 JWT 认证过滤器:



public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
 
    private final AuthenticationManager authenticationManager;
 
    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        this.setPostOnly(true);
    }
 
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse r
2024-09-05



#!/bin/bash
# 设置PostgreSQL的版本和下载路径
POSTGRESQL_VERSION="12.3"
DOWNLOAD_URL="https://ftp.postgresql.org/pub/source/v${POSTGRESQL_VERSION}/postgresql-${POSTGRESQL_VERSION}.tar.gz"
 
# 安装编译依赖
sudo apt-get update
sudo apt-get install -y build-essential zlib1g-dev libssl-dev libreadline-dev libbz2-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
 
# 创建PostgreSQL用户和组
sudo groupadd -r postgres
sudo useradd -r -g postgres postgres
 
# 创建安装目录和数据目录
sudo mkdir -p /opt/postgresql /var/lib/postgresql
sudo chown -R postgres:postgres /opt/postgresql /var/lib/postgresql
sudo chmod -R 700 /var/lib/postgresql
 
# 下载并解压PostgreSQL源码
cd /opt
wget "$DOWNLOAD_URL"
tar -zxvf "postgresql-${POSTGRESQL_VERSION}.tar.gz"
 
# 编译和安装PostgreSQL
cd "postgresql-${POSTGRESQL_VERSION}"
./configure --prefix=/opt/postgresql --bindir=/opt/postgresql/bin --datadir=/var/lib/postgresql --libdir=/opt/postgresql/lib --includedir=/opt/postgresql/include --sysconfdir=/opt/postgresql/etc --docdir=/opt/postgresql/doc --mandir=/opt/postgresql/man --enable-depend --enable-cassert --enable-debug --with-openssl --with-pam --with-ldap --with-libxml --with-libxslt --enable-thread-safety
gmake
sudo gmake install
 
# 配置环境变量
echo 'export PATH=/opt/postgresql/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
 
# 初始化数据库
/opt/postgresql/bin/initdb -D /var/lib/postgresql
 
# 启动PostgreSQL服务
/opt/postgresql/bin/pg_ctl -D /var/lib/postgresql -l logfile start
 
# 创建多实例目录和配置多实例
for PORT in 5433 5434; do
    DATA_DIR="/var/lib/postgresql/${PORT}"
    CONF_FILE="/opt/postgresql/etc/postgresql.conf.${PORT}"
    echo "Creating instance for port ${PORT}..."
    sudo mkdir -p "${DATA_DIR}"
    sudo chown -R postgres:postgres "${DATA_DIR}"
    sudo chmod -R 700 "${DATA_DIR}"
 
    # 配置文件模板并修改端口
    cp /opt/postgresql/etc/postgresql.conf "${CONF_FILE}"
    sed -i "s/port = 5432/port = ${PORT}/" "${CONF_FILE}"
    sed -i "s/data_directory = '\/var\/lib\/postgresql'/data_directory = '\/var\/lib\/postgresql\/${PORT}'/" "${CONF_FILE}"
    sed -i "s/hba_file = '\/var\/lib\/postgresql\/hba.conf'/hba_file = '\/var\/lib\/postgresql\/${PORT}\/hba.conf'/" "${CONF_FILE}"
    sed -i "s/ident_file = '\/var\/lib\/postgresql\/pg_ident.conf'/ident_file = '\/var\/lib\/postgresql\/${PORT}\/pg_ident.conf'/" "${CONF_FILE}"
 
   
2024-09-05

在Spring Boot中连接多个数据库,你可以使用Spring Data JPA或JdbcTemplate,并在application.properties或application.yml中配置不同的数据源。

以下是一个简单的例子,展示如何配置两个不同的数据源:

application.properties:




spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/db_primary
spring.datasource.primary.username=root
spring.datasource.primary.password=secret
 
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/db_secondary
spring.datasource.secondary.username=root
spring.datasource.secondary.password=secret
 
spring.jpa.primary.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.secondary.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

配置类:




@Configuration
public class DataSourceConfig {
 
    @Bean(name = "primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "entityManagerPrimary")
    @Primary
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(
            @Qualifier("primaryDataSource") DataSource dataSource) {
        return entityManagerFactory(dataSource, "primary");
    }
 
    @Bean(name = "entityManagerSecondary")
    public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(
            @Qualifier("secondaryDataSource") DataSource dataSource) {
        return entityManagerFactory(dataSource, "secondary");
    }
 
    private LocalContainerEntityManagerFactoryBean entityManagerFactory(
            DataSource dataSource, String persistenceUnitName) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        em.setPackagesToScan("your.package.for.entities");
        JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setPersistenceUnitName(persistenceUnitName);
        em.setJpaProperties(jpaProperties());
        return em;
    }
 
    private Properties 
2024-09-05

在CentOS 7上安装PostgreSQL开发包postgresql-devel的步骤如下:

  1. 添加PostgreSQL的官方仓库,可以使用Yum的repository功能。首先下载对应的.repo文件:



sudo yum install https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm
  1. 清除缓存并重新加载仓库列表:



sudo yum clean all
sudo yum makecache
  1. 安装PostgreSQL开发包(postgresql-devel):



sudo yum install postgresql-devel

执行上述命令后,PostgreSQL的开发包就会被安装在系统中,这样你就可以编译依赖PostgreSQL的其他软件或者开发PostgreSQL应用了。

2024-09-05

在Qt中使用SQLite进行查询和添加操作,你需要使用QSqlDatabaseQSqlQuery类。以下是一个简单的例子:




#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
 
// 建立数据库连接
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("path_to_your_sqlite_db.db");
 
if (!db.open()) {
    qDebug() << "数据库打开失败:" << db.lastError().text();
    return;
}
 
// 查询操作
QSqlQuery query;
query.exec("SELECT * FROM your_table_name");
while (query.next()) {
    QString column1 = query.value(0).toString();
    // 更多的列处理...
    qDebug() << column1;
}
 
// 添加操作
QString insertSql = "INSERT INTO your_table_name (column1, column2) VALUES (?, ?)";
QSqlQuery insertQuery;
insertQuery.prepare(insertSql);
insertQuery.addBindValue("value1");
insertQuery.addBindValue("value2");
 
if (!insertQuery.exec()) {
    qDebug() << "插入失败:" << insertQuery.lastError().text();
}
 
// 关闭数据库连接
db.close();

确保替换path_to_your_sqlite_db.db为你的SQLite数据库文件路径,your_table_name为你的表名,并且根据你的表结构调整列名和数据类型。

这段代码展示了如何打开一个SQLite数据库,执行一个查询并遍历结果,以及如何准备一个插入语句并执行它。在实际应用中,你需要添加错误处理和其他逻辑以确保程序的健壮性和稳定性。