您好,登錄后才能下訂單哦!
小編給大家分享一下Springboot內(nèi)部服務(wù)調(diào)用方式有哪些,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
啟動(dòng)類添加注解,掃描Eureka 中的全部服務(wù)
@SpringBootApplication @EnableEurekaClient @EnableFeignClients public class LoginServiceApplication { public static void main(String[] args) { new SpringApplicationBuilder(LoginServiceApplication.class).web(true).run(args); } }
pom.xml 添加包 (版本號(hào) 根據(jù)實(shí)際選擇)
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency>
創(chuàng)建接口類
@FeignClient(name="hello-service") //spring service name public interface FeignVehicle { @RequestMapping(value="/hello", method = RequestMethod.GET) @ResponseBody public List<Map> hello(@RequestParam Map<String,String> params); }
實(shí)現(xiàn)類注入此接口類
@Autowired FeignVehicle feignVehicle;
使用的時(shí)候直接按照正常調(diào)用方式即可
Map<String,String> map = new HashMap<String, String>(); feignVehicle.hello(map);
跨服務(wù)調(diào)用的時(shí)候出現(xiàn)token信息取不到,在發(fā)送方添加攔截器
@Configuration public class FeignConfiguration { @Bean public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //當(dāng)前服務(wù)token template.header("Authorization","Bearer " + request.getSession().getId()); //template 接收請(qǐng)求方token } }; } }
請(qǐng)求 啟動(dòng)類
@SpringBootApplication @EnableEurekaClient public class HelloServiceApplication { public static void main(String[] args) { new SpringApplicationBuilder(HelloServiceApplication.class).web(true).run(args); } }
請(qǐng)求Controller
@Controller @RequestMapping("/hello") public class HelloController { @RequestMapping(value="/hello",method = RequestMethod.GET) @ResponseBody public List<Map> hello(@RequestParam Map<String, String> queryParam) { return null; } }
product
服務(wù)作為服務(wù)端,提供了一個(gè) 對(duì)外通信Fegin接口 ProductClient,放在了com.imooc.product.client jar包下
order
服務(wù)作為客戶端,直接引用上面的jar,使用 ProductClient ,啟動(dòng)主類后報(bào)下圖錯(cuò)誤:
多模塊化時(shí),應(yīng)該在order主類上添加下面圈出來(lái)的注解,這樣啟動(dòng)后就能掃描這個(gè)包。
看完了這篇文章,相信你對(duì)“Springboot內(nèi)部服務(wù)調(diào)用方式有哪些”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。