项目中导入Maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
启动8080的项目,接口如下
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
List<User> list = new ArrayList<>();
@GetMapping
public List<User> getUser() {
list.add(new User(1, "张三"));
list.add(new User(2, "李四"));
return list;
}
@GetMapping("/{id}")
public User getUserById(@PathVariable Integer id) {
return new User(id, "法外狂徒张三");
}
@PostMapping
public Boolean add(@RequestBody User user) {
return list.add(user);
}
@PutMapping("/{id}")
public Boolean update(@RequestBody User user, @PathVariable Integer id) {
list.forEach(x ->{
if(x.getId().equals(id)){
x.setUsername(user.getUsername());
}
});
return true;
}
@DeleteMapping("/{id}")
public Boolean delete(@PathVariable Integer id) {
return list.remove(id);
}
启动8081的项目,接口如下
@RestController
public class TestController {
@Resource
private UserApi userApi;
@GetMapping("/list")
public Object getList() {
return userApi.getUser();
}
@GetMapping("/{id}")
public Object getUserById(@PathVariable Integer id) {
return userApi.getUserById(id);
}
@PostMapping("/add")
public Object add(@RequestParam("username") String username,@RequestParam("id") Integer id){
return userApi.addUser(new User(id, username));
}
@PutMapping("/update")
public Object update(@RequestParam Integer id){
return userApi.updateUser(new User(4, "lisi"),id);
}
@DeleteMapping("/delete")
public Object delete(@RequestParam Integer id){
return userApi.deleteUserById(id);
}
8081的项目中创建接口
@RetrofitClient(baseUrl = "http://localhost:8080/")
public interface UserApi {
@GET("user")
List<User> getUser();
@GET("user/{id}")
User getUserById(@Path("id")Integer id);
@POST("user")
Boolean addUser(@Body User user);
@PUT("user/{id}")
Boolean updateUser(@Body User user,@Path("id") Integer id);
@DELETE("user/{id}")
Boolean deleteUserById(@Path("id") Integer id);
}
测试
|