SpringCloud-feign组件
方面微服务之间的调用、访问 因为restTemplate使用虽然简单,但是在访问方需要指定被调用方的微服务名、url,这样在开发过程中、后期要进行为期其实非常麻烦。
SpringCloud提供了feign组件解决
用法类似于mybatis里面的mapper
xml sqlsession.xxxList(“com.woniuxy.product.findById”,”1001”)
mapper interface public List findById(int id) mapper.findById()
使用feign的时候也是通过对应的接口API调用就完事,不需要调用方自己去知道对方微服务名、url是什么,只需要通过接口调就行了
①在父工程的pom里面引入feign的依赖 openfeign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-core</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
②在user模块中引入feign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
③在commons(公共)模块引入feign的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
④被调用方负责在commons模块中去编写接口,内容如下:
在编写接口的时候,可以直接去拷贝handler中的方法,粘贴到接口中,只需要将方法体删除,如果在类上@ReuestMapping指定的前缀url,那么需要给每个方法的url加上该前缀
⑤在需要使用该接口的地方(user模块的handler中)注入该接口,然后将之前restTemplate调用方式替换掉
⑥在user模块的启动类上添加注解扫描该接口所在的包(commons中的)
⑦分别启动eureka、8001、8002、user,浏览器发送url请求
http://localhost/user/all
获得数据,over!
还没有评论,来说两句吧...