Spring Cloud openfeign use

1. Maven adds openFeign dependency

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

Second, the producer code

Producer Controller layer code:

@RestController
@RequestMapping("/user")
public class UserController{
    @Autowired
    private UserService userService
    @RequestMapping("/insertUser")
    public void insertUser(@RequestBody User user){
        userService.insert(user);
    }
    @RequestMapping("/getUserById")
    public User getUserById(@RequestParam String username){
        return userService.getUserById(username);
    }
}

Three, consumer code

Consumer Service layer code:

@Service
@FeignClient("endservice")
public interface UserService{
    @RequestMapping("/user/insertUser")
    public void insertUser(@RequestBody User user);
    @RequestMapping("/user/getUserById")
    public User getUserById(@RequestParam String username);
}

Consumer Controller layer code:

@RestController
@RequestMapping("/user")
public class UserController{
    @Autowired
    private UserService userService
    @RequestMapping("/insertUser")
    public void insertUser(@RequestBody User user){
        userService.insert(user);
    }
    @RequestMapping("/getUserById")
    public User getUserById(@RequestParam String username){
        username=username==null?"":username;        

        return userService.getUserById(username);
    }
}

Note:

1. The method parameters and annotations of the Consumer Service layer must be the same as those of the producer Controller layer or errors will occur.

2. Use of @RequestParam and @RequestBoby

@RequestParam can only receive and pass parameter values ​​of commonly used data types such as String, int, float, etc. Cannot receive and pass data of object type (class)

@RequestBoby can receive and pass data of object type

3. The cause of the 400 error

The parameter passed from the consumer Controller layer to the producer Controller layer is null, set the parameter to the default value

Published 34 original articles · Like1 · Visits 1945

Guess you like

Origin blog.csdn.net/qq_38974638/article/details/105113735