这篇文章主要介绍了Servlet+MyBatis项目如何转Spring Cloud微服务,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
一、项目需求
在开发过程中,由于技术的不断迭代,为了提高开发效率,需要对原有项目的架构做出相应的调整。
二、存在的问题
为了不影响项目进度,架构调整初期只是把项目做了简单的maven管理,引入springboot并未做spring cloud微服务处理。但随着项目的进一步开发,急需拆分现有业务,做微服务处理。因此架构上的短板日益突出。spring cloud config 无法完全应用,每次项目部署需要修改大量配置文件。严重影响开发效率,因此便萌生了对项目架构再次调整的决心。
三、调整建议
为了兼容以前的代码版本,尽量不修改现有的代码结构,以免增加额外的工作量并且为了更好的应用cloud config。
首先,创建JdbcConfigBean类,用以读取配置文件,实例代码入如下(仅供参考):
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@RefreshScope
@Component("jdbcConfigBean")
public class JdbcConfigBean {
@Value("${jdbc.driver}")
private String driver;
@Value("${db1.jdbc.url}")
private String url;
@Value("${db1.jdbc.username}")
private String username;
@Value("${db1.jdbc.password}")
private String password;
@Value("${db2.jdbc.url}")
private String db2_url;
@Value("${db2.jdbc.username}")
private String db2_username;
@Value("${db2.jdbc.password}")
private String db2_password;
// 其他数据源
// 其他配置
// 相应的getter setter 方法
}
其次,创建数据源,代码示例如下(仅供参考):
/**
* xml Mabatis XML配置文件
* @param xml
* @return
**/
public static SqlSessionFactory create(String xml){
JdbcConfigBean jdbcConfigBean = (JdbcConfigBean) SpringContextUtil.getBean("jdbcConfigBean");
Properties properties = new Properties();
properties.setProperty("jdbc.driver", jdbcConfigBean.getDriver());
properties.setProperty("db1.jdbc.url", jdbcConfigBean.getUrl());
properties.setProperty("db1.jdbc.username", jdbcConfigBean.getUsername());
properties.setProperty("db1.jdbc.password", jdbcConfigBean.getPassword());
properties.setProperty("db2.virtual.jdbc.url", jdbcConfigBean.getDb2_url());
properties.setProperty("db2.virtual.jdbc.username", jdbcConfigBean.getDb2_username());
properties.setProperty("db2.virtual.jdbc.password", jdbcConfigBean.getDb2_password());
// 其他属性
try {
Reader reader = Resources.getResourceAsReader(xml);
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
return sqlSessionFactoryBuilder.build(reader, properties);
} catch (IOException e) {
log.error("创建数据源失败:" + e.getMessage());
}
return null;
}
感谢你能够认真阅读完这篇文章,希望小编分享的“Servlet+MyBatis项目如何转Spring Cloud微服务”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。