一、环境
Lombok
JDK 1.8.0_281
MyBatis-Plus 3.4.3
Spring Boot v2.3.7.RELEASE
二、依赖
其他依赖视个人情况添加
<!-- MyBatis-Plus 多数据源-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.6</version>
</dependency>
<!--Hive 配置-->
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>2.1.1</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
<exclusion>
<artifactId>log4j</artifactId>
<groupId>log4j</groupId>
</exclusion>
<exclusion>
<artifactId>log4j-1.2-api</artifactId>
<groupId>org.apache.logging.log4j</groupId>
</exclusion>
<exclusion>
<artifactId>log4j-core</artifactId>
<groupId>org.apache.logging.log4j</groupId>
</exclusion>
<exclusion>
<artifactId>log4j-slf4j-impl</artifactId>
<groupId>org.apache.logging.log4j</groupId>
</exclusion>
<exclusion>
<artifactId>log4j-web</artifactId>
<groupId>org.apache.logging.log4j</groupId>
</exclusion>
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
<exclusion>
<artifactId>jetty-runner</artifactId>
<groupId>org.eclipse.jetty</groupId>
</exclusion>
</exclusions>
</dependency>
可能遇到的问题: Required field ‘client_protocol‘ is unset
三、配置
按照实际情况配置 MySQL 和 Hive 的地址、端口、账号、密码。
# MyBatis-Plus 多数据源
spring:
datasource:
dynamic:
primary: mysql #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
mysql:
url: jdbc:mysql://your_mysql_ip:port/your_database_name?autoReconnect=true&useUnicode=true&characterEncoding=utf8&useSSL=false
username: your_username
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver
hive:
url: jdbc:hive2://your_hive_ip:port/your_database_name
username: your_username
password: your_password
driver-class-name: org.apache.hive.jdbc.HiveDriver
四、代码样例
import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/hive")
public class HiveController {
@Autowired
private JdbcTemplate jdbcTemplate;
// @DS 注解要标在执行 SQL 语句用到的数据源为非主要数据源的方法上,value 为 配置文件中的(此例为 hive)
@DS("hive")
@RequestMapping("/select")
public Object select() {
// 要执行的 SQL
String sql = "SELECT * FROM xxxxxx";
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
log.info(rows.toString());
return rows;
}
}