JAVA development (spring RestFull style Feign usage summary)

Most springboots now use RestFull-style interfaces, and Feign makes remote calls.

1. Introduction of Feign:

Feign is a lightweight RESTful http service client in the Spring Cloud Netflix component. It implements an open source framework for load balancing and Rest calls, encapsulates Ribbon and RestTemplate, and implements interface-oriented programming for webservices, further reducing project coupling. Spend.
Feign has a built-in Ribbon, which is used for client load balancing to call the service of the service registry.
Feign itself does not support SpringMVC annotations. It has its own set of annotations. For easier use, Spring Cloud hatched OpenFeign.
Feign is a declarative and templated HTTP client, which can make the provider unaware, and the consumer can just declare it.
 

2. RestFull style:

http://127.0.0.1:8080/stu/student/mozun  	#查询、get请求
http://127.0.0.1:8080/stu/student/			#新增、post请求
http://127.0.0.1:8080/stu/student/  		#删除、put请求
http://127.0.0.1:8080/stu/student/mozun		#修改、delete请求

Traditional style: Pass directly after the url? Stitching parameter passing

http://127.0.0.1:8080/stu/getStudent?userId=mozun  #查询、get请求
http://127.0.0.1:8080/stu/addStudent			   #新增、post请求
http://127.0.0.1:8080/stu/delStudent?userId=mozun  #删除、get或者post请求
http://127.0.0.1:8080/stu/updateStudent			   #修改、post请求

3. Springboot's RestFull style code writing:

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.ApiOperation;

 
@RestController
@RequestMapping("merchant")
public class MerchantController {

    @Autowired
    private MerchantService merchantService;
    
	@ApiOperation(value = "商户注册", notes = "商户注册")
    @PostMapping("register")
    public ResponseData<String> register(@RequestBody Map<String, Object> param) {
        try {
			String  str = merchantService.register(param);
			return ResponseData.success(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return ResponseData.error();
    }
	
	@ApiOperation(value = "商户查询", notes = "商户查询")
    @PostMapping("select")
    public ResponseData<String> select(@RequestBody Map<String, Object> param) {
        try {
			String  str = merchantService.select(param);
			return ResponseData.success(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return ResponseData.error();
    }
	
	@ApiOperation(value = "商户更新", notes = "商户更新")
    @PostMapping("updateData")
    public ResponseData<String> updateData(@RequestBody Map<String, Object> param) {
        try {
			String  str = merchantService.updateData(param);
			return ResponseData.success(str);
		} catch (Exception e) {
			e.printStackTrace();
		}
        return ResponseData.error();
    }
	
 
}

The controller needs to be annotated with @RestController and @RequestMapping.

Comments on how to pass parameters often:

@RequestBody  

@RequestHeader 

@RequestParam

How to use:

  @RequestBody is mainly used to receive the data in the json string passed from the front end to the back end (the data in the request body);

The most commonly used request body to pass parameters is undoubtedly the POST request, so when using @RequestBody to receive data, it is generally submitted in POST mode. In the same receiving method of the backend, @RequestBody and @RequestParam() can be used at the same time, @RequestBody can only have one at most, and @RequestParam() can have multiple.

Usually, the development interface usually passes the postman test and then is jointly debugged with the front end. Example of the method of passing parameters in the body:

 

 @RequestParam annotation main parameters:

1. value: The name of the parameter passed in the request. If the value of the background interface is not set, it will default to the variable name. For example, if the first parameter in the above figure does not set value="page", the parameter name passed in by the front end must be pageNum, otherwise pageNum will not receive the corresponding data in the background interface

2. required: Whether the parameter is required. The default is true, which means that the corresponding parameter must be passed in the request, otherwise a 404 error will be reported. If it is set to false, when there is no such parameter in the request, it will default to null. For variables of basic data types, it must If there is a value, a null pointer exception will be thrown. If null values ​​are allowed, variables in the interface need to be declared using wrapper classes.

3. defaultValue: The default value of the parameter. If there is no parameter with the same name in the request, the variable defaults to this value. Note that default values ​​can use SpEL expressions, such as "#{systemProperties['java.vm.version']}"

What if multiple parameters with the same name are passed in the request, for example: url?userName=zhl&userName=holley?

In fact, the data format passed in at this time is: "zhl, holley", that is, multiple data are separated by commas. In the background interface, variables of type array or list can be used to receive:

public String requestparam8(@RequestParam(value="userName") String []  userNames) 

或者

public String requestparam8(@RequestParam(value="list") List<String> list) 

@RequestHeader is used to map the header information area data of the request to the parameters of the function processing method.

@RequestMapping(value="/header")  
public String test(  
       @RequestHeader("User-Agent") String userAgent,  
       @RequestHeader(value="Accept") String[] accepts)

Example of information written in the request header:

 

Interface information can be previewed by introducing the Swagger component to facilitate development:

@EnableSwagger2

Swagger is a specification and complete framework for generating, describing, invoking and visualizing RESTful web services. The overall goal is to have the client and the filesystem update at the same rate as the server. Documenting methods, parameters and models is tightly integrated into the server-side code, allowing the API to always stay in sync.

Address: http://127.0.0.1:8080/system namer/ service name/swagger-ui.html#/

 

Guess you like

Origin blog.csdn.net/dongjing991/article/details/131328415