spring-boot integrate with consul client

Setup the consul environment

Please refer to below article
https://blog.csdn.net/yaominhua/article/details/82316287

Add dependency to pom.xml

<dependency>
    <groupId>com.orbitz.consul</groupId>
    <artifactId>consul-client</artifactId>
    <version>1.2.4</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Register the service when application startup

Create the Consul client bean

@Configuration
public class ConsulConfig {

    @Bean
    public Consul consul() {
        // default host is localhost and defalt port is 8500
        return Consul.newClient();
    }

}

Create application listener

public class ConsulRegisterListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Consul consul = event.getApplicationContext().getBean(Consul.class);
        int port = 8080;
        int interval = 10;
        String serviceName = "helloWorldService";
        List<String> tag = new ArrayList<>();
        Map<String, String> meta = new HashMap<>();
        try {
            consul.agentClient().register(port,
                    URI.create("http://localhost:8080/actuator/health").toURL(),
                    interval,
                    serviceName,
                    serviceName,
                    tag,
                    meta);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

}

Add listener to SpringApplication

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication sa = new SpringApplication(Application.class);
        sa.addListeners(new ConsulRegisterListener());
        sa.run(args);
    }

}

Discover the service

Create a server class to store the available servers

public class Server {

    private String host;
    private int port;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

}

Create the discovery service

@Component
public class ServiceDiscovery {

    @Autowired
    private Consul consul;

    public List<Server> getServerList(String serviceName) {
        List<Server> upServerList = new ArrayList<>();
        List<ServiceHealth> availableServers = consul.healthClient().getHealthyServiceInstances(serviceName).getResponse();
        availableServers.forEach(x -> {
            Server server = new Server();
            server.setHost(x.getNode().getAddress());
            server.setPort(x.getService().getPort());
            upServerList.add(server);
        });
        return upServerList;
    }

}

Create the controller to have a test

@RestController
@RequestMapping("helloWorld")
public class HelloWorldController {

    @Autowired
    private ServiceDiscovery serviceDiscovery;

    @RequestMapping(value="serverList/{serviceName}",method=RequestMethod.GET)
    public List<Server> getServerList(@PathVariable("serviceName") String serviceName) {
        return serviceDiscovery.getServerList("serviceName");
    }

}

Use below url to test the result:
http://localhost:8080/helloWorld/serverList/helloWorldService

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot provides easy integration with the Spring Integration framework for implementing messaging and integration patterns. Spring Integration provides support for various messaging protocols, including MQTT, a lightweight publish/subscribe messaging protocol. To integrate Spring Integration with MQTT in Spring Boot, follow these steps: 1. Add the following dependencies to your `pom.xml` file: ``` <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-core</artifactId> </dependency> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> </dependency> ``` 2. Create a configuration class for MQTT integration: ``` @Configuration @EnableIntegration public class MqttIntegrationConfig { @Value("${mqtt.broker.url}") private String brokerUrl; @Value("${mqtt.client.id}") private String clientId; @Bean public MessageChannel mqttInputChannel() { return new DirectChannel(); } @Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); MqttConnectOptions options = new MqttConnectOptions(); options.setServerURIs(new String[] { brokerUrl }); factory.setConnectionOptions(options); return factory; } @Bean public MessageProducer inbound() { MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter( clientId, mqttClientFactory(), "topic1", "topic2"); adapter.setCompletionTimeout(5000); adapter.setConverter(new DefaultPahoMessageConverter()); adapter.setQos(1); return adapter; } @Bean public MessageHandler mqttMessageHandler() { return new MessageHandler() { @Override public void handleMessage(Message<?> message) throws MessagingException { System.out.println("Received MQTT message: " + message.getPayload()); } }; } @Bean public IntegrationFlow mqttInFlow() { return IntegrationFlows.from(inbound()) .handle(mqttMessageHandler()) .channel(mqttInputChannel()) .get(); } } ``` 3. Configure the MQTT broker URL and client ID in your application properties file: ``` mqtt.broker.url=tcp://localhost:1883 mqtt.client.id=myClientId ``` 4. Use the `mqttInputChannel` channel to send messages to the MQTT broker. For example: ``` @Autowired private MessageChannel mqttInputChannel; public void sendMqttMessage(String payload) { mqttInputChannel.send(MessageBuilder.withPayload(payload).build()); } ``` With these steps, you can easily integrate MQTT messaging with your Spring Boot application using Spring Integration.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值