001Diamond学习002使用

源码:

https://gitee.com/banzhu/diamond

https://gitee.com/banzhu/diamond-demo

1 检出源码

淘宝现已不再维护Diamond项目,所以无法直接检出官方原版项目。

这里提供一个可用的链接:

https://gitee.com/banzhu/diamond

因为后面会修改源码,并且还会打包,为了避免对其他项目的干扰,源码下载后可以先在pom.xml里修改一下diamond的版本,改为自己的。

2 准备

2.1 测试项目

搭建一个简单的项目,提供一个在数据库中查询用户信息的接口。

pom.xml文件:

 1 <dependencies>
 2     <dependency>
 3         <groupId>org.springframework.boot</groupId>
 4         <artifactId>spring-boot-starter-web</artifactId>
 5     </dependency>
 6     <dependency>
 7         <groupId>org.mybatis.spring.boot</groupId>
 8         <artifactId>mybatis-spring-boot-starter</artifactId>
 9         <version>2.2.1</version>
10     </dependency>
11     <dependency>
12         <groupId>mysql</groupId>
13         <artifactId>mysql-connector-java</artifactId>
14         <scope>runtime</scope>
15     </dependency>
16     <dependency>
17         <groupId>org.springframework.boot</groupId>
18         <artifactId>spring-boot-starter-test</artifactId>
19         <scope>test</scope>
20     </dependency>
21     <dependency>
22         <groupId>com.alibaba</groupId>
23         <artifactId>druid-spring-boot-starter</artifactId>
24         <version>1.1.14</version>
25     </dependency>
26 </dependencies>
27 <build>
28     <plugins>
29         <plugin>
30             <groupId>org.springframework.boot</groupId>
31             <artifactId>spring-boot-maven-plugin</artifactId>
32         </plugin>
33     </plugins>
34     <resources>
35         <resource>
36             <!-- 指定java目录中存放xml文件 -->
37             <directory>src/main/java</directory>
38             <includes>
39                 <include>**/*.xml</include>
40             </includes>
41         </resource>
42         <resource>
43             <!-- 指定resources目录中存放的文件 -->
44             <directory>src/main/resources</directory>
45             <includes>
46                 <include>**.*</include>
47             </includes>
48         </resource>
49     </resources>
50 </build>

application.properties文件:

# 配置端口
server.port=8082
# 配置项目名
server.servlet.context-path=/demo
# 数据源
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 连接池
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=30
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-wait=60000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
# 扫描
mybatis.mapper-locations=classpath:com/example/diamonddemo/dao/*.xml
# 打印SQL语句
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 开启驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true

建表语句:

1 CREATE TABLE `tbl_user` (
2     `id` INT(11) NOT NULL,
3     `username` VARCHAR(255) NULL DEFAULT NULL,
4     `password` VARCHAR(255) NULL DEFAULT NULL,
5     PRIMARY KEY (`id`) USING BTREE
6 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

DiamondDemoApplication类:

 1 @SpringBootApplication
 2 public class DiamondDemoApplication extends SpringBootServletInitializer {
 3     public static void main(String[] args) {
 4         SpringApplication.run(DiamondDemoApplication.class, args);
 5     }
 6     @Override
 7     protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
 8         return application.sources(DiamondDemoApplication.class);
 9     }
10 }

UserController类:

 1 @RestController
 2 @RequestMapping("/user")
 3 public class UserController {
 4     @Autowired
 5     private UserService userService;
 6     @RequestMapping("/findUser")
 7     public User findUser() {
 8         return userService.findUser();
 9     }
10 }

UserService类:

1 @Service("userService")
2 public class UserService {
3     @Autowired
4     private UserMapper userMapper;
5     @Transactional
6     public User findUser() {
7         return userMapper.findUser();
8     }
9 }

UserMapper类:

1 @Mapper
2 public interface UserMapper {
3     User findUser();
4 }

UserMapper.xml文件:

1 <resultMap id="BaseResultMap" type="com.example.diamonddemo.bean.User">
2     <id column="id" property="id"/>
3     <result column="username" property="username"/>
4     <result column="password" property="password"/>
5 </resultMap>
6 <select id="findUser" resultMap="BaseResultMap">
7     select * from tbl_user where id = 1
8 </select>

2.2 建库建表

安装MySQL数据库。

Diamond默认使用的数据库是diamond,所以需要创建数据库:

1 CREATE DATABASE IF NOT EXISTS `diamond` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
2 USE `diamond`;

Diamond默认使用的配置表是config_info,所以需要创建表:

 1 CREATE TABLE IF NOT EXISTS `config_info` (
 2   `id` bigint(64) unsigned NOT NULL AUTO_INCREMENT,
 3   `data_id` varchar(255) NOT NULL DEFAULT ' ',
 4   `group_id` varchar(128) NOT NULL DEFAULT ' ',
 5   `content` longtext NOT NULL,
 6   `md5` varchar(32) NOT NULL DEFAULT ' ',
 7   `gmt_create` datetime NOT NULL DEFAULT '2010-05-05 00:00:00',
 8   `gmt_modified` datetime NOT NULL DEFAULT '2010-05-05 00:00:00',
 9   PRIMARY KEY (`id`),
10   UNIQUE KEY `uk_config_datagroup` (`data_id`,`group_id`)
11 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC;

2.3 修改父项目

在父项目的pom.xml中,将MySQL的版本改为5.1.27版本。

2.4 修改Server项目

在diamond-server项目中,修改jdbc.properties中的数据库连接信息。

在diamond-server项目中,修改user.properties中的用户和密码,用于服务端的登录。

2.5 修改Utils项目

在diamond-utils项目中,在Constants类有几个需要修改的地方:

 1 // 线上服务器,用于获取ServerAddress
 2 public static final String DEFAULT_DOMAINNAME = "localhost";
 3 // 日常服务器,用于获取ServerAddress
 4 public static final String DAILY_DOMAINNAME = "localhost";
 5 // 服务端的端口号
 6 public static final int DEFAULT_PORT = 8080;
 7 // URI地址,用于获取数据,如果不带IP地址,那么轮换使用ServerAddress
 8 public static final String HTTP_URI_FILE = "/diamond-server/config.co";
 9 // 文件名,用于获取ServerAddress
10 public static final String CONFIG_HTTP_URI_FILE = "/url";

2.6 安装

安装修改了版本号的项目到本地:

1 mvn install

3 部署Server服务端

3.1 打包运行

使用Maven命令将diamond-server项目打成war包。

打包命令,跳过测试:

1 mvn clean package -Dmaven.test.skip=true

将war包放在Tomcat下并启动,默认端口号是8080,默认应用名是diamond-server。

输入用户和密码进入系统,配置dataId和组名,设置配置内容。

3.2 创建文件

在Tomcat服务器的根目录,也就是webapps目录下的ROOT目录中,创建url文件,名称需要和Utils项目中的Constants类中的CONFIG_HTTP_URI_FILE配置的名称一致。

内容为服务器的IP地址:

1 127.0.0.1

3.3 配置信息

在页面上输入user.properties中的用户和密码登录,增加dataId和group,以及content配置信息:

# 数据源
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 连接池
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=30
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-wait=60000
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000

4 配置Client客户端

在测试项目中的pom.xml文件中新增依赖:

 1 <dependency>
 2     <groupId>com.taobao.diamond</groupId>
 3     <artifactId>diamond-client</artifactId>
 4     <version>2.0.5.4.demo-SNAPSHOT</version>
 5 </dependency>
 6 <dependency>
 7     <groupId>com.taobao.diamond</groupId>
 8     <artifactId>diamond-utils</artifactId>
 9     <version>2.0.5.4.demo-SNAPSHOT</version>
10 </dependency>

创建测试方法,注意group和dataId需要使用在页面上创建的配置:

 1 @SpringBootTest
 2 class DiamondDemoApplicationTests {
 3     @Test
 4     void testClient() {
 5         DiamondManager diamondManager = new DefaultDiamondManager("work", "demoId", new ManagerListener() {
 6             public void receiveConfigInfo(String configInfo) {
 7                 System.out.println("receiveConfigInfo" + configInfo);
 8             }
 9             public Executor getExecutor() {
10                 return null;
11             }
12         });
13         String availableConfigureInfomation = diamondManager.getAvailableConfigureInfomation(5000);
14         System.out.println("content : " + availableConfigureInfomation);
15     }
16 }

此时,启动测试项目,数据库仍然是通过配置文件获取的,修改application.properties文件:

# 配置端口
server.port=8082
# 配置项目名
server.servlet.context-path=/demo
# 扫描
mybatis.mapper-locations=classpath:com/example/diamonddemo/dao/*.xml
# diamond
diamond.group=work
diamond.dataId=demoId
# log
logging.level.com.example.diamonddemo.dao=debug

配置Diamond:

 1 @Configuration
 2 @EnableTransactionManagement
 3 public class DataSourceConfig {
 4     @Value("${mybatis.mapper-locations}")
 5     private String mapper;
 6 
 7     @Autowired
 8     private DiamondDataSource diamondDataSource;
 9 
10     @Bean
11     public SqlSessionFactory sqlSessionFactory() throws Exception {
12         SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
13         sqlSessionFactoryBean.setDataSource(diamondDataSource.getObject());
14         sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper));
15         SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
16         sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);
17         sqlSessionFactory.getConfiguration().setLogImpl(StdOutImpl.class);
18         return sqlSessionFactory;
19     }
20 
21     @Bean
22     public SqlSessionTemplate sqlSession() throws Exception {
23         return new SqlSessionTemplate(this.sqlSessionFactory());
24     }
25 }

配置数据源:

 1 @Component
 2 public class DiamondDataSource implements FactoryBean<DruidDataSource>, InitializingBean, DisposableBean {
 3     protected final Logger logger = LoggerFactory.getLogger(DiamondDataSource.class);
 4     @Value("${diamond.group}")
 5     private String group;
 6     @Value("${diamond.dataId}")
 7     private String dataId;
 8     private Properties props;
 9     private DruidDataSource druidDataSource;
10 
11     @Override
12     public void afterPropertiesSet() {
13         this.logger.info("[DiamondDataSource.afterPropertiesSet] Start to load diamond config to environment...");
14         DiamondManager manager = new DefaultDiamondManager(group, dataId, new ManagerListenerAdapter() {
15             @Override
16             public void receiveConfigInfo(String content) {
17                 reloadContent(content);
18             }
19         });
20         String content = manager.getAvailableConfigureInfomation(5000L);
21         reloadContent(content);
22         this.logger.info("[DiamondDataSource.afterPropertiesSet] Finish loading diamond config to environment.");
23     }
24 
25     @Override
26     public void destroy() {
27         if (druidDataSource != null) {
28             druidDataSource.close();
29         }
30     }
31 
32     @Override
33     public DruidDataSource getObject() {
34         return druidDataSource;
35     }
36 
37     @Override
38     public Class<?> getObjectType() {
39         return DruidDataSource.class;
40     }
41 
42     @Override
43     public boolean isSingleton() {
44         return true;
45     }
46 
47     private void reloadContent(String content) {
48         if (StringUtils.isNotEmpty(content)) {
49             if (this.props == null) {
50                 this.props = new Properties();
51             }
52             try {
53                 this.props.load(new StringReader(content));
54             } catch (IOException e) {
55                 this.logger.error("[DiamondDataSource.loadContent] Diamond exception : {}", e.getMessage());
56             }
57         }
58         if (druidDataSource == null) {
59             druidDataSource = new DruidDataSource();
60             druidDataSource.setUrl(this.props.getProperty("spring.datasource.url"));
61             druidDataSource.setUsername(this.props.getProperty("spring.datasource.username"));
62             druidDataSource.setPassword(this.props.getProperty("spring.datasource.password"));
63             druidDataSource.setDriverClassName(this.props.getProperty("spring.datasource.driver-class-name"));
64             druidDataSource.setInitialSize(Integer.parseInt(this.props.getProperty("spring.datasource.druid.initial-size")));
65             druidDataSource.setMaxActive(Integer.parseInt(this.props.getProperty("spring.datasource.druid.max-active")));
66             druidDataSource.setMinIdle(Integer.parseInt(this.props.getProperty("spring.datasource.druid.min-idle")));
67             druidDataSource.setMaxWait(Long.parseLong(this.props.getProperty("spring.datasource.druid.max-wait")));
68             druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(this.props.getProperty("spring.datasource.druid.time-between-eviction-runs-millis")));
69             druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(this.props.getProperty("spring.datasource.druid.min-evictable-idle-time-millis")));
70         } else {
71             try {
72                 druidDataSource.restart();
73                 druidDataSource.setUrl(this.props.getProperty("spring.datasource.url"));
74                 druidDataSource.setUsername(this.props.getProperty("spring.datasource.username"));
75                 druidDataSource.setPassword(this.props.getProperty("spring.datasource.password"));
76             } catch (Exception e) {
77                 e.printStackTrace();
78             }
79         }
80     }
81 }

启动项目后,如果Diamond中的配置发生更改,会使用新的配置重新获取数据源。

 

posted @ 2022-02-09 10:17  执笔未来  阅读(118)  评论(0编辑  收藏  举报