您的位置:首页 > 理论基础 > 计算机网络

springboot开发笔记(3.web层http、异常)

2017-11-18 10:51 344 查看

部分代码

web层代码:joy_bms(http请求和统一异常)

https://github.com/bjjoy/joy_bms.git

http对接service层代码:auth_service项目git地址

https://github.com/bjjoy/service_auth

1.前言

本文给出请求处理层(web)代码,内容包括

(1)引入okhttp3,与auth_service进行交互获取数据。

(2)统一异常处理。

(3)引入log4j2

(4)测试

2.目录结构



(1)base:返回码和对应文字说明ResponseCode、统一返回结构ResponseResult

(2)exception:可以maven打jar包放到其他项目。

GlobalExceptionHandler统一异常处理:指定自动捕获controller层抛出的异常,写入日志,返回ResponseResult。

OperationException:自定义业务异常,避免四处写try、catch。例:joy_bms通过请求删除用户角色role, auth_service查库发现有user与role关联,可以直接throws operationException(1001,‘与角色关联禁止删除’)。

(3)service:可以maven打jar包放到其他项目

BaseHttpService:定义get、post方法。

AuthHttpService:继承BaseHttpService,定义自己的地址。

@Service
@ConfigurationProperties(prefix = "joy.service")
public class AuthHttpService extends BaseHttpService{

private String auth = "http://localhost:8010";

@Override
public String getDomain() {
return auth;
}

public String getAuth() {
return auth;
}

public void setAuth(String auth) {
this.auth = auth;
}
}


这里用到@ConfigurationProperties。说明前缀joy.service的属性可以定义到properties文件,joy.service.auth是获取properties文件中的值,如果没有用默认值http://localhost:8010。properties文件内容如下

server.port=8020
joy.service.auth=http://127.0.0.1:8010
logging.config=classpath:log4j2.xml


说明:有新的service,新建ClassHttpService extends BaseHttpService,properties文件中定义好自己的地址。万一迷茫了有service换了服务器,换了地址修改properties文件就好。

(4)util:只有数据格式转换

(5)web:测试程序

3.pom引入的jar(log4j2、configuration、okhttp3)

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.3.0</version>
</dependency>


4.观后感

(1)捕获异常要写入日志文件,保留痕迹,统一处理挺方便

(2)okhttp3用着也很简介明了

(3)web层负责处理与页面交互数据格式转换,auth_service专注业务逻辑即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: