spring boot项目访问外部http请求的解决方案

Spring-Boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求。针对这一需求以前的做法就是访问外部请求都要经过httpClient 需要专门写一个方法,来发送http请求,这个就不说了,网上一搜全都是现成的方法。springboot 实现外部http请求 是通过FeignClient来请求http数据的,特别简单并且非常实用的一个注解就可以搞定。

采用Feign进行消费

第一步:在maven项目中添加依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>2.0.2.RELEASE</version>
</dependency>

第二步:编写接口,放置在service层

@FeignClient(url="${crm.server.url}",name="crmServer")
public interface naturalVisitCustomerService {
    @RequestMapping(value = "/view/naturalVisit/addNaturalVisitCustomer",method = RequestMethod.POST)
    public JSONObject saveCustomer(@RequestParam("customerName") String customerName, @RequestParam("customerPhone") String customerPhone,
                                   @RequestParam("source") String source, @RequestParam("intention") String intention);
}

这里的crm.server.url 是配置在properties配置文件中的  结构是ip地址和端口号

crm.server.url = https://devcrm.yijia.com:5555

/view/naturalVisit/addNaturalVisitCustomer  是接口名字   

第三步:要在启动的java类上加 @EnableFeignClients这个注解

@SpringBootApplication(exclude = PageHelperAutoConfiguration.class)
@MapperScan("com.yijia.website.module.*.dao")
@EnableTransactionManagement
@EnableCaching
@EnableRedisHttpSession
@EnableFeignClients
public class CmsApplication {

	public static void main(String[] args){
		SpringApplication.run(CmsApplication.class, args);
	}
}

第四步:在需要调用的地方调用刚刚写的接口

    @ResponseBody
    @RequestMapping("/saveQuote")
    public String saveQuoteInfo(Quote quote){
        quote.setCreateTime(new Date());
        if (quote.getQuoteId() != null){
            return quoteService.updateQuote(quote);
        }
        addCustomerToCRM(quote);
        return quoteService.saveQuote(quote);
    }


    // 新加入的方法,专门用于调用刚刚写的放入到service层的接口
    private void addCustomerToCRM(Quote quote) {
        String customerName = Optional
                .ofNullable(quote.getCustomerName())
                .orElse("自然到访客户");
        try{
            JSONObject result = naturalVisitCustomerService.saveCustomer(customerName, quote.getCustomerPhone(), CmsConst.SITE, CmsConst.CONSUMER);
            log.info("自然到访客户接口 保存客户 结果 === {}",result.toString());
        }catch (Exception e){
            log.error("自然到访客户接口 保存客户 异常 === {}",e.getMessage());
        }
    }

参考文献

spring boot 访问外部http请求

posted @ 2019-09-18 10:23  No8g攻城狮  阅读(287)  评论(0编辑  收藏  举报