springboot整合consul

服务提供方

核心依赖(springboot依赖省略)

        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-consul-discoveryartifactId>
        dependency>
 

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控制台可以看到注册的服务
springboot整合consul_第1张图片

消费方(使用feign调用)

核心依赖

		
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-consul-discoveryartifactId>
        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 实现服务提供者和服务消费者
springboot整合consul_第2张图片

你可能感兴趣的:(springcloud,spring,boot,java,java-consul)