spring boot整合jpa構建微服務以及服務呼叫
阿新 • • 發佈:2019-01-27
一、Maven構建專案
1、訪問http://start.spring.io/
2、選擇構建專案的基本資訊,參考下圖:
3、點選Generate Project下載專案壓縮包
4、下載後解壓到本地,並以Import -> Existing Maven Projects的方式,匯入eclipse中
5、匯入後,專案結構如下:
二、加入web,jpa依賴
<!-- 核心模組,包括自動配置支援、日誌和YAML --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <!-- 測試依賴,測試模組,包括JUnit、Hamcrest、Mockito --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- ==========以上兩個依賴為pom檔案中預設的兩個模組 --> <!-- mvc web專案依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- JPA依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- mysql依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
三、增加jpa配置檔案
spring.datasource.url = jdbc:mysql://localhost:3306/codesafe?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username = root spring.datasource.password = 123456 spring.datasource.driverClassName = com.mysql.jdbc.Driver # Specify the DBMS spring.jpa.database = MYSQL # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update) spring.jpa.hibernate.ddl-auto = update # Naming strategy spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy # stripped before adding them to the entity manager) spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
將上面的配置檔案拷貝到application.properties檔案中,注意:spring boot的配置檔案都是放到properties檔案中,不需要額外的xml和java配置檔案
四、編寫實體類
@Entity @Table(name="GITHUB") public class GitHubEntity implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column(name="ID") private Integer id; @Column(name="CREATE_TIME") @Temporal(TemporalType.TIMESTAMP) private Date createTime = new Date(); @Column(name="SPRIDER_SOURCE") private String spriderSource; @Column(name="SPRIDER_URL") private String spriderUrl; @Column(name="USER_NAME") private String userName; @Column(name="PROJECT_URL") private String projectUrl; @Column(name="CODE_URL") private String codeUrl; @Lob @Column(name="CODE_SNIPPET") private String codeSnippet; @Column(name="SENSITIVE_MESSAGE") private String sensitiveMessage; }
以上程式碼省略get,set方法。
五、編寫資料訪問層
@Transactional
public interface GitHubRepository extends CrudRepository<GitHubEntity, Integer>{
}
如果對jpa的用法不是很熟悉的,可以參考我的另一篇部落格:
六、編寫controller
@RestController
public class GitHubController {
@Autowired
private GitHubRepository repository;
@RequestMapping("/github/get")
public GitHubEntity getCodeSnippet(int id){
return repository.findOne(id);
}
/**
* @return the repository
*/
public GitHubRepository getRepository() {
return repository;
}
/**
* @param repository the repository to set
*/
public void setRepository(GitHubRepository repository) {
this.repository = repository;
}
}
@RestController的意思就是controller裡面的方法都以json格式輸出,不用再寫什麼jackjson配置的了!
七、啟動主程式
啟動主程式,開啟瀏覽器訪問http://localhost:8080//github/get?id=721,就可以看到效果了,有木有很簡單!效果如下:
{"id":721,"createTime":1480908930000,"spriderSource":"github","spriderUrl":"https://github.com/Datartisan/travelsky/blob/master/export_flight_final_data.py","userName":"Datartisan","projectUrl":"https://github.com/Datartisan/travelsky","codeUrl":"https://github.com/Datartisan/travelsky/blob/master/export_flight_final_data.py","codeSnippet":"# coding: utf-8\n \nimport os\nimport json\n \nDATA_FOLDER_PATH \nEXPORT_DATA_FILE_PATH \n \ndef ():\n \n= flight_final_data []\n \nfor root, dirs, files os.walk():\nfor file_name files:\n= flight_data_file os.path.join(root, file_name)\nwith (flight_data_file) f:\n= flight_data json.loads( f.read() )\n \n- flight_final_data.append(flight_data[])\n# print('processing: {}'.format(flight_data_file)) \n \nwith (, ) f:\n f.write(json.dumps(flight_final_data))\n \n \nif :\n export_flight_final_data()\n","sensitiveMessage":""}
八、呼叫spring boot服務
下面寫個簡單的方法,來呼叫上面的這個服務,程式碼如下:
public class HttpClientService {
protected CloseableHttpClient httpclient;
/**
* get請求HttpClient返回實體或error
* @param address 請求地址
* @return
*/
public void getGithubCodeSnippetByID(int id) {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 建立httpget.
HttpGet httpget = new HttpGet("http://localhost:8080//github/get?id="+id);
System.out.println("executing request " + httpget.getURI());
// 執行get請求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 獲取響應實體
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 列印響應狀態
System.out.println(response.getStatusLine());
if (entity != null) {
// 列印響應內容長度
System.out.println("Response content length: " + entity.getContentLength());
// 列印響應內容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉連線,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
測試程式碼如下:
public class HttpClientServiceTest {
@Test
public void test(){
HttpClientService service = new HttpClientService();
service.getGithubCodeSnippetByID(721);
}
}
測試結果如下:
Response content: {"id":721,"createTime":1480908930000,"spriderSource":"github","spriderUrl":"https://github.com/Datartisan/travelsky/blob/master/export_flight_final_data.py","userName":"Datartisan","projectUrl":"https://github.com/Datartisan/travelsky","codeUrl":"https://github.com/Datartisan/travelsky/blob/master/export_flight_final_data.py","codeSnippet":"# coding: utf-8\n \nimport os\nimport json\n \nDATA_FOLDER_PATH \nEXPORT_DATA_FILE_PATH \n \ndef ():\n \n= flight_final_data []\n \nfor root, dirs, files os.walk():\nfor file_name files:\n= flight_data_file os.path.join(root, file_name)\nwith (flight_data_file) f:\n= flight_data json.loads( f.read() )\n \n- flight_final_data.append(flight_data[])\n# print('processing: {}'.format(flight_data_file)) \n \nwith (, ) f:\n f.write(json.dumps(flight_final_data))\n \n \nif :\n export_flight_final_data()\n","sensitiveMessage":""}通過上面的幾個步驟,就基本可以實現通過spring boot來實現微服務了