2024-09-01

MyBatis 是一个优秀的持久层框架,用于简化数据库操作。以下是 MyBatis 的核心组件及其整合示例:

  1. SqlSessionFactory: 用于创建 SqlSession 的实例。
  2. SqlSession: 用于执行 SQL 命令,获取映射器实例,管理事务。
  3. Mapper: 由开发者编写的接口,用于定义操作数据库的方法。

整合示例代码:




// 配置文件 mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/myapp"/>
        <property name="username" value="root"/>
        <property name="password" value="password"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/myapp/Mapper.xml"/>
  </mappers>
</configuration>
 
// Mapper 接口
package org.myapp;
public interface UserMapper {
  User selectUser(int id);
}
 
// Mapper XML 文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.myapp.UserMapper">
  <select id="selectUser" resultType="User">
    SELECT * FROM users WHERE id = #{id}
  </select>
</mapper>
 
// 使用 MyBatis 的示例代码
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
  UserMapper mapper = session.getMapper(UserMapper.class);
  User user = mapper.selectUser(1);
  // 处理 user 对象
}

在这个示例中,我们首先定义了 MyBatis 的配置文件 mybatis-config.xml,其中包含了环境配置、数据源和 Mapper 文件的位置。接着定义了一个 Mapper 接口和对应的 XML 文件,其中包含了 SQL 查询语句和映射规则。最后,我们通过 SqlSessionFactory 创建了 SqlSession,并通过它获取了 UserMapper 实例,执行了 selectUser 方法。

2024-09-01

在IntelliJ IDEA中使用Maven archetype创建Spring Boot项目的步骤如下:

  1. 打开IntelliJ IDEA。
  2. 点击 Create New Project
  3. 在弹出的对话框中,选择 Maven
  4. 选择或填写相关的GroupId和ArtifactId。
  5. Location 中填写项目的目录路径。
  6. 点击 Next,然后选择或者输入Spring Boot的archetype。
  7. 填写 Version 如果需要的话,然后点击 Next
  8. 填写项目名称和描述,点击 Finish

以下是使用Maven archetype创建Spring Boot项目的命令行示例:




mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=my-spring-boot-app \
  -DarchetypeGroupId=org.springframework.boot \
  -DarchetypeArtifactId=spring-boot-starter-parent \
  -DarchetypeVersion=2.5.6 \
  -DinteractiveMode=false

在IntelliJ IDEA中,上述步骤会自动完成。如果需要手动执行命令,可以在项目的根目录下打开终端,并运行以上Maven命令。

2024-09-01



import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
 
@Component
public class AuthorizationGlobalFilter implements GlobalFilter, Ordered {
 
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 示例:检查请求中是否包含有效的API密钥
        String apiKey = exchange.getRequest().getQueryParams().getFirst("apiKey");
        if (apiKey == null || !apiKey.equals("mySecretApiKey")) {
            // 如果API密钥无效,则返回401未授权状态码
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 如果API密钥有效,则继续请求处理
        return chain.filter(exchange);
    }
 
    @Override
    public int getOrder() {
        // 确保此过滤器在其他过滤器之前运行
        return -1;
    }
}

这段代码定义了一个全局过滤器,用于检查进入API网关的请求中是否包含有效的API密钥。如果密钥无效,则过滤器会直接返回HTTP状态码401,表示请求未被授权。这种方式可以用来实现简单的API访问控制,在实际应用中可以根据需要进行更复杂的权限控制。

2024-09-01

在CentOS 7上安装Docker,并学习常用的Docker命令,接着使用Docker安装常见的组件,如Tomcat、MySQL和Redis。

  1. 安装Docker:



sudo yum install -y yum-utils
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
sudo yum install -y docker-ce docker-ce-cli containerd.io
sudo systemctl start docker
sudo systemctl enable docker
  1. Docker常用命令:



# 启动Docker
sudo systemctl start docker
 
# 停止Docker
sudo systemctl stop docker
 
# 重启Docker
sudo systemctl restart docker
 
# 查看Docker状态
sudo systemctl status docker
 
# 查看Docker版本
docker --version
 
# 查看所有容器
docker ps -a
 
# 查看运行中的容器
docker ps
 
# 拉取镜像
docker pull 镜像名称
 
# 创建并启动容器
docker run -d -p 主机端口:容器端口 --name 容器名称 镜像名称
 
# 停止容器
docker stop 容器名称或ID
 
# 删除容器
docker rm 容器名称或ID
 
# 删除镜像
docker rmi 镜像名称或ID
  1. 使用Docker安装Tomcat:



docker run -d -p 8080:8080 --name my-tomcat tomcat:9.0
  1. 使用Docker安装MySQL:



docker run -d -p 3306:3306 --name my-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw mysql:5.7
  1. 使用Docker安装Redis:



docker run -d -p 6379:6379 --name my-redis redis:5.0

以上命令需要在具备sudo权限的CentOS 7系统上执行。这些命令展示了如何安装Docker,启动和使用它来运行Tomcat、MySQL和Redis等常见的Web服务。

2024-09-01

在Spring Boot项目中使用SpringBootServletInitializer可以将项目打包成WAR文件,并部署到支持Servlet API的Web容器中。以下是步骤和示例代码:

  1. 在Spring Boot主类上扩展SpringBootServletInitializer并重写configure方法。
  2. pom.xml中设置打包方式为war
  3. 构建项目并生成WAR文件。
  4. 部署到Web容器。

示例代码:

主类:




import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
 
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
 
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(MyApplication.class);
    }
 
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

pom.xml:




<packaging>war</packaging>
 
<!-- 其他依赖 -->

构建项目:




mvn clean package

生成的WAR文件通常位于target/目录下。

部署到Tomcat或其他容器时,确保容器配置正确,并且没有其他相关的Web服务器(如Jetty或Undertow)配置在类路径下。

2024-09-01

在Spring Boot中,你可以加载自定义的YAML配置文件,并将其属性绑定到一个配置类中。以下是一个简单的例子:

  1. 创建自定义配置文件 custom-config.yml:



custom:
  property: value
  1. 创建配置类来绑定YAML中的属性:



package com.example.demo.config;
 
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ConfigurationProperties(prefix = "custom")
public class CustomConfig {
    private String property;
 
    public String getProperty() {
        return property;
    }
 
    public void setProperty(String property) {
        this.property = property;
    }
}
  1. 在Spring Boot应用的主类或配置类中添加 @EnableConfigurationProperties(CustomConfig.class) 注解:



package com.example.demo;
 
import com.example.demo.config.CustomConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
 
@SpringBootApplication
@EnableConfigurationProperties(CustomConfig.class)
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  1. 在需要使用配置的地方注入 CustomConfig:



import com.example.demo.config.CustomConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component
public class SomeComponent {
 
    private final CustomConfig customConfig;
 
    @Autowired
    public SomeComponent(CustomConfig customConfig) {
        this.customConfig = customConfig;
    }
 
    public void printCustomProperty() {
        System.out.println(customConfig.getProperty());
    }
}

确保 custom-config.yml 位于 src/main/resources 目录下,与Spring Boot的标准配置文件分开管理。当Spring Boot应用启动时,它会自动加载这个配置文件并将属性绑定到 CustomConfig 类中,你可以在应用程序的任何部分通过依赖注入来访问这些属性。

2024-09-01

在CentOS 8中部署Tomcat和Jenkins可以通过以下步骤进行:

  1. 安装Java环境

    Tomcat和Jenkins都需要Java环境,确保系统已安装Java。




sudo dnf install java-11-openjdk-devel
java -version
  1. 安装Tomcat



sudo dnf install tomcat
sudo systemctl enable --now tomcat

检查Tomcat是否运行:




sudo systemctl status tomcat

浏览器访问 http://<服务器IP>:8080 确认Tomcat安装成功。

  1. 安装Jenkins

添加Jenkins仓库:




sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import https://pkg.jenkins.io/redhat-stable/jenkins.io.key

安装Jenkins:




sudo dnf install jenkins

启动并启用Jenkins服务:




sudo systemctl start jenkins
sudo systemctl enable jenkins

检查Jenkins状态:




sudo systemctl status jenkins

浏览器访问 http://<服务器IP>:8080 并按照Jenkins初始化向导进行配置。

注意:确保防火墙允许访问8080端口。




sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

以上步骤可能会根据系统的实际情况稍有变化,请确保在执行前检查最新的安装指南和更新的配置要求。

2024-09-01

在Spring Boot中,我们可以使用application.properties文件或者application.yml文件来配置我们的应用。

  1. 使用application.properties文件

application.properties文件中,我们可以定义一些常用的配置,例如数据库连接信息,服务器端口等。




# application.properties
app.name=MyApp
app.description=This is a Spring Boot application
 
server.port=8080
 
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=myuser
spring.datasource.password=mypass

然后在代码中,我们可以使用@Value注解来获取这些属性的值。




import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
@Component
public class AppConfig {
 
    @Value("${app.name}")
    private String appName;
 
    @Value("${app.description}")
    private String appDescription;
 
    // getters and setters
}
  1. 使用application.yml文件

application.yml是一种更为高级的配置方式,它可以提供更好的可读性和可维护性。




# application.yml
app:
  name: MyApp
  description: This is a Spring Boot application
 
server:
  port: 8080
 
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: myuser
    password: mypass

在代码中,我们可以使用@ConfigurationProperties注解来绑定这些属性。




import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
@Component
@ConfigurationProperties(prefix="app")
public class AppConfig {
 
    private String name;
    private String description;
 
    // getters and setters
}

在这两种配置方式中,application.properties更为基础,而application.yml则提供了更多的灵活性和可读性,是当前的主流配置方式。

2024-09-01

Spring Boot 3 在 Spring Boot 2 的基础上构建,提供了许多改进和新特性。以下是一些 Spring Boot 3 的核心特性:

  1. 支持最新的 Java 版本:Spring Boot 3 将支持 Java 21 及以上版本。
  2. 支持最新的 Spring 框架版本:Spring Boot 3 将支持 Spring 6 及以上版本的主要版本。
  3. 自动配置:Spring Boot 3 将继续提供自动配置,简化应用程序配置。
  4. 启动速度优化:Spring Boot 3 将优化启动时间,尤其是在使用云原生特性时。
  5. 安全性提升:Spring Boot 3 将提高安全性,包括密码学和认证方面的改进。
  6. 代码生成器:Spring Boot 3 将提供更先进的代码生成工具,帮助开发者更快速地构建应用程序。

由于 Spring Boot 3 尚未正式发布,因此上述特性可能会随着版本的发布而变化。在实际开发中,我们通常关注 Spring Boot 的主要版本,如 Spring Boot 2.x 和 Spring Boot 1.x,新版本发布时,关注官方发布的文档和新特性即可。

2024-09-01

整合Spring Boot和ShardingSphere-JDBC以及MyBatis-Plus进行数据分片的示例代码如下:

  1. pom.xml中添加依赖:



<dependencies>
    <!-- ShardingSphere JDBC -->
    <dependency>
        <groupId>org.apache.shardingsphere</groupId>
        <artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
        <version>您的ShardingSphere版本</version>
    </dependency>
    <!-- MyBatis-Plus -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>您的MyBatis-Plus版本</version>
    </dependency>
    <!-- 数据库驱动,以MySQL为例 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>您的数据库驱动版本</version>
    </dependency>
</dependencies>
  1. application.yml中配置ShardingSphere和MyBatis-Plus:



spring:
  shardingsphere:
    datasource:
      names: ds0,ds1
      ds0:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3306/ds0
        username: root
        password:
      ds1:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://localhost:3306/ds1
        username: root
        password:
    sharding:
      tables:
        t_order:
          actual-data-nodes: ds$->{0..1}.t_order_$->{0..1}
          table-strategy:
            inline:
              sharding-column: order_id
              algorithm-expression: t_order_$->{order_id % 2}
    props:
      sql:
        show: true
 
mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.example.demo.model
  1. 创建实体类和Mapper接口:



// 实体类 TOrder.java
public class TOrder {
    private Long orderId;
    // 省略其他字段和getter/setter方法
}
 
// Mapper接口 TOrderMapper.java
@Mapper
public interface TOrderMapper extends BaseMapper<TOrder> {
    // 使用MyBatis-Plus提供的基本CRUD方法
}
  1. 配置MyBatis-Plus分页插件:



@Configuration
public class MyBatisPlusConfig {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}
  1. 使用Shardi