springcloud下json的传递
首先服务中心要先开启,服务注册、消费注册。这里服务我使用的是eurekaclient;消费使用ribbon来做负载均衡。下面进入正题:@Autowiredprivate HelloService helloService;@RequestMapping(value = "/hi")public void hi(@RequestBody Student studen
·
首先服务中心要先开启,服务注册、消费注册。这里服务我使用的是eurekaclient;消费使用ribbon来做负载均衡。下面进入正题:
@Autowired
private HelloService helloService;
@RequestMapping(value = "/hi")
public void hi(@RequestBody Student student){
helloService.hi(student);
}
这里是前端传递的json数据,没什么好说的,相信大家都能看懂
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public void hi(Student student)
{
System.out.println(student);
HttpHeaders headers=new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Student> entity=new HttpEntity<Student>(student,headers);
ResponseEntity<Student> studentResponseEntity=restTemplate.exchange("http://SERVICE-HI/hi", HttpMethod.POST,entity,Student.class);
Student student1=studentResponseEntity.getBody();
System.out.println(student);
}
}
这里是重点了,利用httpHeaders来设置访问工程时的消息头,由消息头可以看出此次访问是以json形式去请求,再利用httpentity把要传递的对象和消息封装起来,用restTemplate发送请求
@RequestMapping("/hi")
public String home(@RequestBody Student student){
System.out.println(student);
return "i am from port:"+port;
}
这是服务者接受的代码,也没什么好说的,总之还是要多写多看
代码地址:https://github.com/love-dl-forever/SpringCloud
更多推荐
已为社区贡献1条内容
所有评论(0)