java - spring boot连接池理解

标签 java spring spring-boot database-connection connection-pool

在 Spring boot application.properties 文件中,我们有以下选项:

server.tomcat.max-threads = 100
server.tomcat.max-connections = 100
spring.datasource.tomcat.max-active = 100
spring.datasource.tomcat.max-idle = 30

这是我的存储库类

public interface UserRepository extends JpaRepository<Users,Integer>{}

这是服务类

@Service
@Transactional(rollbackFor = Exception.class)
public class UserService {

    @Autowired
    private UserRepository userRepository;
    public User getUserById(Integer id){return userRepository.findOne(id)}

问题是,userRepository 如何创建与数据库的连接,以及它会使用我的应用程序属性文件中的连接池。我来自 JDBC 和 hibernate,在那里我使用 DataManager、DataSource、Connection 类来使用连接池,但在 spring boot 中,我没有任何代码行,这些类一切正常

最佳答案

它像以前一样工作,但是使用 Spring Boot,Spring 为您完成了更多任务。
使用或不使用 Spring,作为 UserRepository 的 DAO 类不直接操作数据源,也不直接创建 JDBC 连接。
这些由您正在使用的 EntityManagerFactory 实现操作。
使用 Spring-Hibernate,您仍然需要配置 EntityManagerFactory
现在使用 Spring Boot,您无需配置它。
它已为您完成。

Spring Boot 的新功能是您现在还可以配置服务器数据源属性:

server.tomcat.max-threads = 100
server.tomcat.max-connections = 100
spring.datasource.tomcat.max-active = 100
spring.datasource.tomcat.max-idle = 30

因为 Tomcat 服务器可以由 Spring Boot 应用程序本身启动。

This part of the Spring Boot documentation给出数据源实现的优先顺序:

Production database connections can also be auto-configured using a pooling DataSource. Here’s the algorithm for choosing a specific implementation:

We prefer the Tomcat pooling DataSource for its performance and concurrency, so if that is available we always choose it.

Otherwise, if HikariCP is available we will use it.

If neither the Tomcat pooling datasource nor HikariCP are available and if Commons DBCP is available we will use it, but we don’t recommend it in production and its support is deprecated.

Lastly, if Commons DBCP2 is available we will use it.


更新: 根据 Spring Boot 2.x,HikariCP 是默认的连接池机制。

关于java - spring boot连接池理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46766624/

相关文章:

java - Java 中的音乐(暂停/停止)

Eclipse 中的 Java Spring 检查

java - Spring 启动 : Error in API access : Failed to connect to <domainName>

java - 如何在显示JSP后执行hibernate session.close()以避免lazy=false

java - Hybris 6 是否使用 hibernate 或者在任何过去的版本中使用过

java - 如何将对象传递给 UnitTest 类中被测试的类?

java - Spring Boot 测试无法解决存储库依赖关系

java - Spring Boot Apache Camel Quartz JDBC 调度器

java - Java 如何记录一个类的不变量?

java - 我怎么知道准备好的语句是否被缓存?