使用RestTemplate 实现Http请求:
服务提供者:
applicatgion.yml
-------------------------
server:
port: 8080
spring:
application:
name: comsumer-order
UserController 控制层:
@RestController
public class UserController
{
@Autowired
private UserService userService;
@PostMapping("get/user/{id}")
public UserDTO getUser(@PathVariable String id,@RequestBody UserDTO userDTO )
{
return userService.getUser(id,userDTO);
}
}
----------------------------------------
@Service
public class UserServiceImpl implements UserService
{
@Override
public UserDTO getUser(String id, UserDTO userDTO)
{
userDTO.setName(String.format("getUserDTO %s-%s",userDTO.getName(),id));
userDTO.setCurrentTime(new Date());
return userDTO;
}
}
----------------------------------------
@Data
public class UserDTO implements Serializable
{
private static final long serialVersionUID = -2391272212394096956L;
private long id;
private String name;
private String password;
@JSONField(format = "yyyy-MM-dd HH:mm:ss,SSS")
private Date currentTime;
}
服务消费者:
application.yml
server:
port: 8081
spring:
application:
name: consumer-1
privide:
consumer: http://127.0.0.1:8080/get/user/
UserController 控制层:
@RestController
public class UserController
{
@Autowired
private UserService userService;
@Autowired
private RestTemplate restTemplate;
@Value("${privide.consumer}")
private String baseURL;
@GetMapping("consumer")
public ResponseEntity<UserDTO> getUserDTO(long id)
{
UserDTO user = userService.getUser(id);
String url = baseURL+id;
ResponseEntity<UserDTO> userDTOResponseEntity = restTemplate.postForEntity(url, user, UserDTO.class);
return userDTOResponseEntity;
}
}
UserService 层:
@Service
public class UserServiceImpl implements UserService
{
@Value("${spring.application.name}")
private String appName;
@Override
public UserDTO getUser(long id)
{
UserDTO userDTO = new UserDTO();
userDTO.setName(appName);
userDTO.setId(id);
userDTO.setPassword(appName);
return userDTO;
}
}
启动类:
@SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class);
}
@Bean
public RestTemplate getRestemplate()
{
return new RestTemplate();
}
}
RestTemplate 中封装了实用的httpclient 工具类方便使用。