您的位置:首页 > 编程语言 > Java开发

spring boot整合jpa构建微服务以及服务调用

2016-12-06 19:12 816 查看
一、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的用法不是很熟悉的,可以参考我的另一篇博客:

http://blog.csdn.net/liuchuanhong1/article/details/52042477

六、编写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来实现微服务了 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐