4、创建SpringCloud server 消费者(Feign

2019-05-31  本文已影响0人  SmartBin

先创建一个普通的SpringBoot项目,然后添加SpringCloud服务消费者所需的配置即可。

pom.xml 添加内容

<!--使用SpringBoot1.5.3版本-->
  <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>1.5.3.RELEASE</version>
       <relativePath/> <!-- lookup parent from repository -->
   </parent>

<dependencies>

         <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

         <!--引入eureka服务发现依赖-->
         <dependency>
               <groupId>org.springframework.cloud</groupId>
               <artifactId>spring-cloud-starter-eureka</artifactId>
           </dependency>

        <!--引入feign功能依赖-->
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-feign</artifactId>
       </dependency>

</dependencies>

<dependencyManagement>
           <dependencies>
               <dependency>
                   <groupId>org.springframework.cloud</groupId>
                   <artifactId>spring-cloud-dependencies</artifactId>
                   <version>Camden.SR7</version>
                   <type>pom</type>
                   <scope>import</scope>
               </dependency>
           </dependencies>
</dependencyManagement>

application.yml文件配置

spring:
  application:
    name: eureka-consumer-feign  #定义服务名

server:
  port: 8084

eureka:
  client:
    serviceUrl:
      #指定服务端地址
      defaultZone: http://localhost:8000/eureka/

启动类添加@EnableFeignClients 、@EnableDiscoveryClient 注解

@EnableFeignClients   //开启Feign的功能
@EnableDiscoveryClient    //开启服务发现功能
@SpringBootApplication
public class SpringcloudClientFeignApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(SpringcloudClientFeignApplication.class).web(true).run(args);
    }

}

创建调用服务接口DescClient (接口名随便定义)

@FeignClient(value = "db-service")  //注解里db-service指的是提供服务的服务名
public interface DescClient {

    @RequestMapping(value = "/user/{name}")
    String getForEntity(@PathVariable("name") String name);

}

接口名为DescClient ,在Controller中调用该接口。

创建Controller类

@RestController
public class MainController {
    //注入上述定义的接口
    @Autowired
    private DescClient descClient;

    @RequestMapping("/user/{name}")
    public String get(@PathVariable("name") String name){
        return descClient.getForEntity(name);
    }
    
}

在Controller中注入定义的服务调用接口,在Controller中像是在调用本地接口一样。

最后启动该项目,可以在浏览器中测试该项目,使用该路径(/bin 为name参数,在数据库中有该条记录) http://localhost:8084/user/bin 即可访问有服务消费者提供的接口。

上一篇下一篇

猜你喜欢

热点阅读