本文要讲解三点
1 spring boot 项目创建
2 spring boot 项目基础上面创建netty项目(下一篇)
3 netty websocket支持wss以及配置负载均衡(下一篇)
No1 spring boot 项目创建
对于很多想入门spring boot的童鞋,看到mybatis的集成使用,不用在代码中手写sql语句,是一种多么优雅的行为,基于这个基础,遂决定将spring boot的项目创建介绍一番。本文将配合大量截图,实现一个彻底的完全的项目创建。
Step1 打开idea,选择Create New Project
Step2 选择左边的Spring Initializr,然后选择Next
Step3 直接Next(本文仅仅为了演示demo创建,因此不需要设置其他的信息,例如名称或者groupId等),java版本自行按照需要选择
Step4 选择左边的选项SQL,选择Spring Boot的版本为2.3.5(本文使用的idea是.03版本,可能和最新的版本存在不同,最新的版本mybatis可能支持最新的Spring Boot了)
选择完Spring Boot版本,我们在下面选择MyBatis Framework,然后点击Next
Step5 选择保存项目的位置以及项目的名称,例如demo,如此项目就初步创建成功了
Step6 直接创建完项目之后,我们可以看到偏右上角,有”DemoApplication”,我们选择他旁边的三角形,直接运行项目,项目显示”Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.”,这个提示我们需要配置项目了。
Step7 我们开始配置数据库连接,以及mapper,我们在resources目录下创建application.yml文件,编写配置如下
debug: false
spring:
datasource:
url: jdbc:mysql://数据库IP:3306/miao_database?characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai
username: username
password: password
driver-class-name: com.mysql.jdbc.Driver
hikari:
minimum-idle: 8
maximum-pool-size: 30
connection-test-query: SELECT 1
max-lifetime: 10000
connection-timeout: 50000
jmx:
enabled: false
mybatis:
type-aliases-package: com.dasi.miaowar.model
mapper-locations: classpath:/mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
同时在pom.xml中添加如下依赖
mysql
mysql-connector-java
org.springframework.boot
spring-boot-starter-web
截图
新增的一个依赖,用于数据库链接 一个这是以web服务器的方式启动该项目。如此我们选择运行项目,发现项目可以跑了,不过我们还没有编写接口,测试项目。我们在DemoApplication类文件的同层,建立controller目录,在这里面创建逻辑文件:IndexController类。内容如下
@RestController
@RequestMapping("/api")
publicclassIndexController{
@RequestMapping("index")
@ResponseBody
publicStringindex(){
return"index";
}
}
引入各个包,并且开始运行,在浏览器中输入接口地址
http://127.0.0.1:8080/api/index
注意我设置了端口为8080
发现反击了index,说明接口运行成功。
Step8
开始使用mybatis,使用mybatis,进行数据库表操作
在controller的同级目录,分别创建
mapper,model,service文件夹;在resouces目录中创建mapper文件夹。
我们在前一个mapper文件夹下面添加
FeedMapper接口
@Mapper
@Component
public interface FeedMapper {
Integer getCount();
}
在model中添加
Feed类
public class Feed {
private int id;
}
在service中添加
FeedBiz接口
public interface FeedBiz {
Integer getCount();
}
在service目录下面新增Impl文件夹,在这里面添加
FeedBizImpl 类实现接口FeedBiz
@Service
@Transactional
public class FeedBizImpl implements FeedBiz {
@Autowired
private FeedMapper feedMapper;
@Override
public Integer getCount() {
return feedMapper.getCount();
}
}
在后一个mapper文件夹下面添加FeedMapper.xml文件,内容如下
SELECT count(0) from miao_recommendation
至此,我们使用mybatis的配置基本完成,现在我们使用之,调取getCount查看效果
我们重新编写IndexController类
@RestController
@RequestMapping("/api")
publicclassIndexController{
@Autowired
privateFeedBizfeedBiz;
@RequestMapping("index")
@ResponseBody
publicStringindex(){
Integercount=feedBiz.getCount();
if(count==null){
count=0;
}
return"index:"+count;
}
}
在浏览器中再次调用
http://127.0.0.1:8080/api/index即完成了mybatis的应用