服务端开发中,有很多常识是相通的,例如mysql,redis,http协定等。
基于这些根底,在编程语言上的转变并不艰难。
本文次要从上面几点登程,讲述如何疾速从php开发转为java开发:
- 应用框架构建web我的项目 - 10min
- 罕用数据结构对应和概念转变 - 5min
- 操作Mysql数据库和发送http申请 - 15min
应用框架构建我的项目
先看下PHP和JAVA对应的我的项目工具和框架:
PHP | JAVA | |
---|---|---|
项目管理工具 | composer | maven |
框架 | Laravel或Thinkphp | SpringBoot |
java中,maven是项目管理工具,实现装置依赖,打包等性能,是一个我的项目的终点,通过pom.xml配置文件治理依赖。SpringBoot实质上就是一个maven的依赖包。
相比php的框架,SpringBoot原生提供的性能并不多,然而能够通过maven很不便的加载其余性能的依赖
罕用的java开发IDE是idea,社区版是收费的,能够间接在官网下载,根本能满足开发需要。
创立我的项目
须要的筹备工作,下载idea。在零碎中装置maven和jdk,能够间接通过idea装置,也能够去官网下载安装。
能够应用官方网站:https://start.spring.io/ ,来创立SpringBoot我的项目,如下图,这里咱们抉择Spring Web依赖。
下载解压后,能够看到外面曾经有了pom.xml文件,并退出了SpringBoot的依赖,应用idea加载文件夹:
我的项目引入后,能够看到目录构造曾经建好,接下来实现一个web api解决http申请,如下:
package com.abc.webtest.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class TestController { @GetMapping("/test") public String test(){ return "hello"; }}
- 新建一个controller文件夹,用来寄存所有解决http申请的类
- 在php的框架里通常会把url和解决办法的映射放在一个route.php文件里
- 在SpringBoot中次要应用注解的形式指定url的解决办法
之后能够间接启动利用,默认的端口是:8080。启动后就可在浏览器中拜访:http://localhost:8080/test,返回hello
- 如果要批改启动的默认端口,能够在
application.yml
中增加如下配置。
server: port: 9999
application.yml
是SpringBoot中用来治理配置的文件,大部分主动配置的组件的配置能够写到这里。例如下面的服务启动端口。
罕用数据结构对应和概念转变
如果要问php中最罕用的数据结构是什么?置信大多数答案都是array
。
绝对的在java开发中罕用的数据结构是ArrayList
和HashMap
,它们能够看成是array
的拆分,一种简略的对应关系为:
PHP | JAVA |
---|---|
array('a','b','c') | ArrayList |
array(a'=>1,'b'=>2,'c'=>3) | HashMap |
理解对应关系有助于在开发中更好的应用对应的构造。
在开发中还有一些概念上的转变:
变量定义
- php是弱类型语言,定义变量时能够不指定类型,应用比拟灵便,但也容易出问题。
- java是强类型语言,每个变量都要指定类型,不能给变量赋值为别的类型。
每次申请的变量遗留
- 应用php-fpm形式提供服务时,每次申请完结时都会把创立的变量回收,包含动态变量。所以申请间不会有影响
- SpringBoot提供服务时,是始终运行的,意味着上次申请创立或批改的变量可能会影响下一次申请,造成问题,这个须要特地留神。尤其是对动态变量的应用。
操作Mysql数据库
日常开发中,最罕用的性能就是操作数据库和通过http申请调用接口了(微服务调用次要依赖服务框架,这里不波及)。
代码中操作数据库,通常包含两大部分:
ORM长久层映射:负责代码和数据表的操作转换,把表映射为一个对象,通过对象来操作表
- php中次要是各框架提供的,例如
Laravel
中的Eloquent Model
类 - java中较受欢迎的是
mybatis-plus
,也是把每个表映射为一个实体类
- php中次要是各框架提供的,例如
数据库连贯层
- php中是
PDO
+pdo_mysql
扩大 - java中能够应用
druid
+mysql-connector
- php中是
上面就介绍下在java中应用mybatis-plus
+ druid
+ mysql-connector
操作数据库中的一张表,次要分5步。
1.通过maven在pom.xml中加载这三个依赖
在应用SpringBoot框架时,会常常用到主动配置,在我的项目启动时主动创立须要的对象。
这里间接应用对应的starter包,能够在我的项目启动时,主动创立数据库连接池等对象。
<!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.1</version> </dependency> <!-- mybatis plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency>
2.创立表的实体和Mapper
当初库中有一张表,表名是:main_user
CREATE TABLE `main_user` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `password` varchar(100) NOT NULL, `user_name` varchar(100) NOT NULL, `user_phone` varchar(40) NOT NULL, `score` int(11) DEFAULT '0', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`user_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
要操作这张表,首先须要创立一个类作为该表的映射,类名就是MainUser,类的成员就是表中的字段,每个字段的类型须要与数据库中的绝对应,罕用的类型能够很容看进去,其余字段能够百度一下JdbcType类型和Java类型的对应关系。
public class MainUser extends Model<MainUser> { private static final long serialVersionUID = 1L; @TableId(value = "user_id", type = IdType.AUTO) private Integer userId; private String password; private String userName; private String userPhone; private Integer score; private LocalDateTime createTime; private LocalDateTime updateTime;}
而后创立一个Mapper用于操作这个类,就叫做MainUserMapper
。
因为这里应用了mybatis-plus
,Mapper能够间接应用很多底层办法,能够只定义一个空接口。
import com.abc.webtest.db.entity.MainUser;import com.baomidou.mybatisplus.core.mapper.BaseMapper;public interface MainUserMapper extends BaseMapper<MainUser> {}
3.在SpringBoot中设置Mapper的包名
SpringBoot的IOC能够间接生成可用的接口实现对象,只有在启动时指定要扫描的Mapper所在的包名。
@SpringBootApplication@MapperScan("com.abc.webtest.db.mapper") //这个就是mapper包,一个库中表的mapper都放在这里public class WebtestApplication { public static void main(String[] args) { SpringApplication.run(WebtestApplication.class, args); }}
4.在application.yml中设置mysql的配置
将连贯mysql须要的地址,用户名,明码写入application.yml中:
spring: datasource: druid: url: jdbc:mysql://localhost:3306/test_db?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456
5.在controller中操作表
这里简略展现下对表的操作。
在SpringBoot中,底层的IOC会负责类之间的援用关系,即在A中援用B,不须要手动创建对象,而是应用Resource
等注解。
上面两个申请实现了对表的插入和按id查问。
@RestControllerpublic class TestController { //这里会将要应用的对象加载到该类中 @Resource MainUserMapper mainUserMapper; @GetMapping("/test") public String test() { return "hello"; } //定义post申请,这里框架底层会间接将body外面的json数据,按key名赋值给参数中的对象 @PostMapping("user/register") public Boolean userRegister(@RequestBody MainUser mainUser) { mainUserMapper.insert(mainUser); return true; } @GetMapping("user/info") public MainUser userInfo(Integer userId) { MainUser mainUser = new MainUser(); return mainUserMapper.selectById(userId); }}
发送HTTP申请
在开发中,零碎的内部资源除了数据库,最多的就是其余的服务了,这里介绍下java中拜访http接口的办法。
在php中,拜访http的底层根本都是用curl
扩大的相干性能。
在java中,一个比拟根底的包是httpclient
,首先在pom.xml中引入这个包。
<!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency>
写一个HttpUtil
类作Http的对立申请
这里应用@Componet
注解,它的作用是通知Spring框架将该类作为一个bean加载到IOC中,供其余类应用。
@Componentpublic class HttpUtil { CloseableHttpClient client = HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom() .setConnectTimeout(500) //连贯超时工夫,单位毫秒,按理论状况调整 .build()) .setDefaultSocketConfig(SocketConfig.custom() .setSoTimeout(2 * 1000) //申请响应超时工夫,单位毫秒,这里设为2秒,按理论状况调整 .build()) .build(); public String get(String url) throws IOException { HttpGet httpGet = new HttpGet(url); try (CloseableHttpResponse httpResponse = client.execute(httpGet)) { HttpEntity httpEntity = httpResponse.getEntity(); return EntityUtils.toString(httpEntity, "UTF-8"); } } public String post(String url, Map<String, String> params) throws IOException { HttpPost httpPost = new HttpPost(url); CloseableHttpResponse httpResponse = null; try { //这里应用了Jackson作为json转换工具,在spring-web依赖中曾经引入,能够间接应用 ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(params); StringEntity stringEntity = new StringEntity(json, "UTF-8"); httpPost.setEntity(stringEntity); httpPost.addHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); httpResponse = client.execute(httpPost); return EntityUtils.toString(httpResponse.getEntity()); } finally { if (httpResponse != null) { httpResponse.close(); } } }}
在controller中应用
这里创立两个简略的接口,应用GET和POST办法别离调用了两个收费的api。
同样应用Resource
加载HttpUtil
类的对象到controller中。
@RestControllerpublic class TestController { @Resource HttpUtil httpUtil; @GetMapping("inaword") public String inAWord() throws IOException { return httpUtil.get("http://api.lkblog.net/ws/api.php"); } @GetMapping("create/random") public String createRandom(String name, String phone) throws IOException { Map<String, String> params = new HashMap<>(); params.put("name", name); params.put("job", phone); return httpUtil.post("https://reqres.in/api/users", params); }}
通过下面的介绍,心愿能帮忙大家更快的上手java开发。
残缺的pom.xml和application.xml
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.abc</groupId> <artifactId>webtest</artifactId> <version>0.0.1-SNAPSHOT</version> <name>webtest</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.1</version> </dependency> <!-- mybatis plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>6.0.6</version> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
application.yml
server: port: 9999spring: datasource: druid: url: jdbc:mysql://localhost:3306/test_db?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC username: root password: 123456
文章中工程的源代码地址:https://gitee.com/dothetrick/...
以上内容属集体学习总结,如有不当之处,欢送在评论中斧正