服務端開發中,有很多知識是相通的,例如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;
@RestController
public 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查詢。
@RestController
public 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中,供其他類使用。
@Component
public 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中。
@RestController
public 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: 9999
spring:
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/webtest
以上內容屬個人學習總結,如有不當之處,歡迎在評論中指正