springboot整合consul

服务提供方

核心依赖(springboot依赖省略)

        <!--consul-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
 <!--       <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-config</artifactId>
        </dependency>
        这个consul-config我暂时还不清楚什么用,但如果引入这个jar,application.yml文件名就要改名(bootstrap.yml),否则就找不到对应的配置内容
        -->

application.yml

server:
  port: 81
spring:
  application:
    name: project-dao
  cloud:
    consul:
      host: 192.168.233.136
      port: 8500
      discovery:
        instance-id: ${spring.application.name}:${server.port} #这个id作为唯一识别的id必填
        service-name: consul-dao
        heartbeat:
          enabled: true  #不打开心跳机制,控制台会显示红叉

启动类加注解:@EnableDiscoveryClient

@SpringBootApplication
@MapperScan("com.meng.dao")
@EnableDiscoveryClient
public class DaoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DaoApplication.class  , args);
    }
}

提供查询的接口

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getAll")
    public List<User> getUserAll(){
        return userService.findAll();
    }
}

启动服务后,consul控制台可以看到注册的服务
在这里插入图片描述

消费方(使用feign调用)

核心依赖

		<!--openfein的依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

        <!--consul-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

application.yml
discovery.register设置为false就不会将消费者服务注册到consul

server:
  port: 80
spring:
  application:
    name: project-web
  cloud:
    consul:
      host: 192.168.233.136
      port: 8500
      discovery:
        register: false

启动类加注解@EnableFeignClients

@SpringBootApplication
@EnableFeignClients
public class WebApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebApplication.class , args);
    }
}

FeignClient类用于调用服务

@FeignClient("consul-dao")
public interface UserIao {
    @GetMapping("/user/getAll")
    List<User> getUserAll();
}

controller调用即可

@RestController
public class PortalController {

    @Autowired
    private UserIao userIao;

    @GetMapping("/getAllUser")
    public List<User> getAllUser(){
        return userIao.getUserAll();
    }

我这里直接使用Feign去调用服务了,也可以使用原生的方式进行调用,我没有试过,可以参考:
Consul 实现服务提供者和服务消费者
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值