壹、涉及微服务结构相关的知识点
从零搭建微服务SpringCloud(二)新建一个SpringCloud项目
贰、实现代码
1、导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
2、resources目录创建application.yml文件
#自定义端口号
server:
port: 7000
#自定义服务注册名
spring:
application:
name: HTTP-SERVICE
3、搭建启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HttpServiceRequestStart {
public static void main(String[] args) {
SpringApplication.run(HttpServiceRequestStart.class,args);
}
}
4、创建服务类
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class HttpServiceRequestService {
private Logger logger = LoggerFactory.getLogger(HttpServiceRequestService.class);
public void saveNotify(String reqBody){
logger.info("reqBody="+reqBody);
com.alibaba.fastjson.JSONObject resObj = JSONObject.parseObject(reqBody);
System.out.println(resObj);
}
}
5、搭建控制层
import com.cloud.start.com.service.HttpServiceRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@RestController
@CrossOrigin
@RequestMapping(value = "/first", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class HttpServiceRequestController {
@Autowired
private HttpServiceRequestService httpServiceRequestService;
@RequestMapping(value = "/request" ,method = RequestMethod.POST)
public String one(HttpServletRequest result){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(result.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while((line = br.readLine())!=null){
sb.append(line);
}
String reqBody = sb.toString();
httpServiceRequestService.saveNotify(reqBody);
}catch (Exception e){
e.printStackTrace();
}
return "success";
}
}
叁、参数详解
1、服务层详解
在服务层中,有代码为
com.alibaba.fastjson.JSONObject resObj = JSONObject.parseObject(reqBody);
我们进入JSONObject.parseObject(reqBody);的parseObject(String text)中看一下
如上图,第一行为Object obj = parse(text);
继续进入到parse方法
我们发现,parse方法是用来将String类型转为JSON类型
回到parseObject(String text)
如图,如果obj是JSONObject创建的对象,那么直接将obj强转为JSONObject对象并返回
如果不是JSONObject创建的对象,则将obj转为JSON后强转为JSONObject对象并返回,如果无法转换,则抛出新异常“can not cast to JSONObject”,无法转换为 JSON 对象。
2、控制层详解
@RequestMapping(value = "/first", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
MediaType参数介绍