源码:

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文件:

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.1</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.14</version></dependency>
</dependencies>
<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins><resources><resource><!-- 指定java目录中存放xml文件 --><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource><resource><!-- 指定resources目录中存放的文件 --><directory>src/main/resources</directory><includes><include>**.*</include></includes></resource></resources>
</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

建表语句:

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

DiamondDemoApplication类:

@SpringBootApplication
public class DiamondDemoApplication extends SpringBootServletInitializer {public static void main(String[] args) {SpringApplication.run(DiamondDemoApplication.class, args);}@Overrideprotected SpringApplicationBuilder configure(SpringApplicationBuilder application) {return application.sources(DiamondDemoApplication.class);}
}

UserController类:

@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@RequestMapping("/findUser")public User findUser() {return userService.findUser();}
}

UserService类:

@Service("userService")
public class UserService {@Autowiredprivate UserMapper userMapper;@Transactionalpublic User findUser() {return userMapper.findUser();}
}

UserMapper类:

@Mapper
public interface UserMapper {User findUser();
}

UserMapper.xml文件:

<resultMap id="BaseResultMap" type="com.example.diamonddemo.bean.User"><id column="id" property="id"/><result column="username" property="username"/><result column="password" property="password"/>
</resultMap>
<select id="findUser" resultMap="BaseResultMap">select * from tbl_user where id = 1
</select>

2.2 建库建表

安装MySQL数据库。

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

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

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

CREATE TABLE IF NOT EXISTS `config_info` (`id` bigint(64) unsigned NOT NULL AUTO_INCREMENT,`data_id` varchar(255) NOT NULL DEFAULT ' ',`group_id` varchar(128) NOT NULL DEFAULT ' ',`content` longtext NOT NULL,`md5` varchar(32) NOT NULL DEFAULT ' ',`gmt_create` datetime NOT NULL DEFAULT '2010-05-05 00:00:00',`gmt_modified` datetime NOT NULL DEFAULT '2010-05-05 00:00:00',PRIMARY KEY (`id`),UNIQUE KEY `uk_config_datagroup` (`data_id`,`group_id`)
) 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类有几个需要修改的地方:

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

2.6 安装

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

mvn install

3 部署Server服务端

3.1 打包运行

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

打包命令,跳过测试:

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地址:

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文件中新增依赖:

<dependency><groupId>com.taobao.diamond</groupId><artifactId>diamond-client</artifactId><version>2.0.5.4.demo-SNAPSHOT</version>
</dependency>
<dependency><groupId>com.taobao.diamond</groupId><artifactId>diamond-utils</artifactId><version>2.0.5.4.demo-SNAPSHOT</version>
</dependency>

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

@SpringBootTest
class DiamondDemoApplicationTests {@Testvoid testClient() {DiamondManager diamondManager = new DefaultDiamondManager("work", "demoId", new ManagerListener() {public void receiveConfigInfo(String configInfo) {System.out.println("receiveConfigInfo" + configInfo);}public Executor getExecutor() {return null;}});String availableConfigureInfomation = diamondManager.getAvailableConfigureInfomation(5000);System.out.println("content : " + availableConfigureInfomation);}
}

此时,启动测试项目,数据库仍然是通过配置文件获取的,修改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:

@Configuration
@EnableTransactionManagement
public class DataSourceConfig {@Value("${mybatis.mapper-locations}")private String mapper;@Autowiredprivate DiamondDataSource diamondDataSource;@Beanpublic SqlSessionFactory sqlSessionFactory() throws Exception {SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();sqlSessionFactoryBean.setDataSource(diamondDataSource.getObject());sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper));SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);sqlSessionFactory.getConfiguration().setLogImpl(StdOutImpl.class);return sqlSessionFactory;}@Beanpublic SqlSessionTemplate sqlSession() throws Exception {return new SqlSessionTemplate(this.sqlSessionFactory());}
}

配置数据源:

@Component
public class DiamondDataSource implements FactoryBean<DruidDataSource>, InitializingBean, DisposableBean {protected final Logger logger = LoggerFactory.getLogger(DiamondDataSource.class);@Value("${diamond.group}")private String group;@Value("${diamond.dataId}")private String dataId;private Properties props;private DruidDataSource druidDataSource;@Overridepublic void afterPropertiesSet() {this.logger.info("[DiamondDataSource.afterPropertiesSet] Start to load diamond config to environment...");DiamondManager manager = new DefaultDiamondManager(group, dataId, new ManagerListenerAdapter() {@Overridepublic void receiveConfigInfo(String content) {reloadContent(content);}});String content = manager.getAvailableConfigureInfomation(5000L);reloadContent(content);this.logger.info("[DiamondDataSource.afterPropertiesSet] Finish loading diamond config to environment.");}@Overridepublic void destroy() {if (druidDataSource != null) {druidDataSource.close();}}@Overridepublic DruidDataSource getObject() {return druidDataSource;}@Overridepublic Class<?> getObjectType() {return DruidDataSource.class;}@Overridepublic boolean isSingleton() {return true;}private void reloadContent(String content) {if (StringUtils.isNotEmpty(content)) {if (this.props == null) {this.props = new Properties();}try {this.props.load(new StringReader(content));} catch (IOException e) {this.logger.error("[DiamondDataSource.loadContent] Diamond exception : {}", e.getMessage());}}if (druidDataSource == null) {druidDataSource = new DruidDataSource();druidDataSource.setUrl(this.props.getProperty("spring.datasource.url"));druidDataSource.setUsername(this.props.getProperty("spring.datasource.username"));druidDataSource.setPassword(this.props.getProperty("spring.datasource.password"));druidDataSource.setDriverClassName(this.props.getProperty("spring.datasource.driver-class-name"));druidDataSource.setInitialSize(Integer.parseInt(this.props.getProperty("spring.datasource.druid.initial-size")));druidDataSource.setMaxActive(Integer.parseInt(this.props.getProperty("spring.datasource.druid.max-active")));druidDataSource.setMinIdle(Integer.parseInt(this.props.getProperty("spring.datasource.druid.min-idle")));druidDataSource.setMaxWait(Long.parseLong(this.props.getProperty("spring.datasource.druid.max-wait")));druidDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(this.props.getProperty("spring.datasource.druid.time-between-eviction-runs-millis")));druidDataSource.setMinEvictableIdleTimeMillis(Long.parseLong(this.props.getProperty("spring.datasource.druid.min-evictable-idle-time-millis")));} else {try {druidDataSource.restart();druidDataSource.setUrl(this.props.getProperty("spring.datasource.url"));druidDataSource.setUsername(this.props.getProperty("spring.datasource.username"));druidDataSource.setPassword(this.props.getProperty("spring.datasource.password"));} catch (Exception e) {e.printStackTrace();}}}
}

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

001Diamond学习002使用相关推荐

  1. python视频学习002(2017年老男孩最新全栈python第2期视频教程)---电脑简史

    申明 计算机简史 申明 最近开始系统的学习python,跟着老男孩的python教程一起学习并记录下相关内容,2017年老男孩最新全栈python第2期视频教程 相关视频下载请参考我上一篇博客,上面介 ...

  2. 【Java学习002】Java-ArrayList源码解析

    ArrayList源码解析 1.1底层数据结构 定义:实现List接口的可扩容数组实现. 数组特点: 查询快:数组开辟的是连续空间,所以可以依靠索引进行快速查询. 增删慢:每次删除元素,都需要更改数组 ...

  3. JS 特效学习 002:图片渐显

    没图的JS都是耍流氓!!! 一.实现效果: 二.原理分析: 在介绍实现步骤之前,先跟大家说说图像渐显的本质问题:如何实现渐渐显示? 渐显的 本质 是 改变图像的透明度,从完全透明逐渐增加非透明度,直到 ...

  4. 少说话多写代码之Python学习002——环境搭建

    一.安装包安装 本机为windows所以主要介绍windows下的环境搭建, for windows的python安装包下载地址: http://www.python.org/download/ 按照 ...

  5. C4D R19学习之002视图窗口与基本操作

    C4D R19学习 002视图窗口与基本操作 1.视图操作以及视图窗口功能 ·Alt+鼠标左键--旋转视图: 在按住alt键进行旋转时,光标的位置就是该目标旋转时所绕的点,想看哪一块,旋转时,光标就要 ...

  6. 计算co1课程的平均成绩mysql_MySQL练习

    一.表关系 二.创建数据库和表 (一)创建数据库 创建数据库test2,用于存放上述表 mysql> create database test2 defaultcharset utf8 coll ...

  7. Datawhale组队学习周报(第002周)

    Datawhale组队学习周报(第002周) (一)当下 本周(02月22日~02月28日),我们正在进行5门开源内容的组队学习.一共建立了6个学习群,参与人数1080人.到目前为止,有4门课开源内容 ...

  8. 002柿饼派GUI模组学习之AnimatedImage控件调试

    本文声明:本文为个人学习柿饼派显示模组的相关记录与经验. 002柿饼派GUI模组学习之AnimatedImage 控件调试 1.认识AnimatedImage控件   AnimatedImage是动态 ...

  9. 代码 马佳义_【图像融合学习笔记002】图像融合论文及代码网址整理总结(2)——红外与可见光图像融合...

    写在前面的话: 本篇博文主要整理汇总一下现有的红外与可见光图像融合算法(文章和代码).适当地,也会整理出作者的学术主页.整理这些的初衷,是为了方便自己,顺便也给同领域的研究者在找代码等方面提供些许便利 ...

  10. OpenCV学习笔记#002 OpenCV相机检校例程运行

    OpenCV学习笔记#002 OpenCV相机检校例程运行 OpenCV学习笔记#002 OpenCV相机检校例程运行 所需文件 修改文件 修改in_VID5.xml 修改VID5.xml VS 设置 ...

最新文章

  1. 近亿台物联网设备或遭劫持,这家IoT云平台遭遇“灾难性”入侵事件
  2. windows下安装使用couchdb
  3. Python 3.9要发布啦,快来看看有哪些新特性?
  4. java中multiply用法_java中BigDecimal加减乘除基本用法
  5. [2020.10.25NOIP模拟赛]序列【Splay】
  6. 左侧固定,右侧自适应的布局方式(新增评论区大佬教的方法)
  7. 集成 websocket 的四种方案
  8. ICCV2021 Oral-新任务!新数据集!康奈尔大学提出了类似VG但又不是VG的PVG任务
  9. 深度学习(六十六)生成模型、最大化似然、KL散度
  10. ThreadLocal 原理和使用场景分析
  11. 什么是银行行号,银行联行号有哪些功能?
  12. 34. 脱壳篇-FSG压缩壳、ImportREC修复IAT输入表的使用,令一种寻找OEP方式
  13. 2018上半年五款最畅销高速数据采集卡,你get了吗?
  14. String.intern源码
  15. VS找到w3wp.exe 附加到23wp.exe进行debug程序调试
  16. 数据共享,如何拆掉那些“部门的墙”?by 傅一平
  17. 微信小程序:修复图片音频全新升级带特效喝酒神器源码
  18. HTTP断点续传以及缓存问题
  19. Mybatis狂神说完整笔记
  20. 国内主要的广告联盟背景

热门文章

  1. 第一代操盘手图解“庄家操盘五部曲”;股市不可不知的赚钱法则!
  2. 卓有成效的管理者—第一章 卓有成效是可以学会的
  3. html a hover css,CSS中的a:hover表示什么
  4. 男人成为富翁必备五大特质
  5. 网络编程(二)- 检查网络的工具
  6. 基于osgEarth的空间态势三维场景视点控制与卫星轨道绘制
  7. 冰汽时代机器人不用热_冰汽时代机器流玩法 寒霜朋克机器人流玩法怎么玩
  8. 从零到上亿用户,我是如何一步步优化MySQL数据库的?(建议收藏)
  9. SUN SPARC T4-4电源故障引起的宕机
  10. java的GUI:个人所得税计算