springboot中restTemplate通讯的三种方式

需要学习视频资料请加qq 1686763368 

@Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
   // private RestTemplate restTemplate;

    /**
     * resttemplate 三种调用方法
     *
     * @return
     */
    @RequestMapping
    public String Test() {
        //resttemplate 三种调用方法

        //第一种方式(直接使用restTemplate,url写死)
//        RestTemplate restTemplate = new RestTemplate();
//        String response = restTemplate.getForObject("http://localhost:8080/msg", String.class);
        //第二种方式(利用loadBalancerClient通过应用获取url,然后再使用restTemplate)
        RestTemplate restTemplate = new RestTemplate();
        ServiceInstance serviceInstance = loadBalancerClient.choose("服务名");
        String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort(), "/msg");
        String response = restTemplate.getForObject(url, String.class);
        //第三种方式(利用@LoadBalanced,可在restTemplate里使用应用的名字)
       //String response = restTemplate.getForObject("http://localhost:8080/msg", String.class);
        return response;
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate (){
        return new RestTemplate();
    }

 

 

 

Java 微服务通讯方式主要分为同步通讯和异步通讯,以下是具体方式及其实现方法: ### 同步通讯 - **RESTful API**:基于 HTTP 协议,简单易用,广泛应用于各种微服务架构。在 Java 中可使用 Spring Boot 框架实现。 ```java // 服务提供者 import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class ProviderApplication { @GetMapping("/hello") public String hello() { return "Hello from provider!"; } public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } } // 服务消费者 import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.client.RestTemplate; @SpringBootApplication public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject("http://localhost:8080/hello", String.class); System.out.println(result); } } ``` - **gRPC**:高性能、开源的远程过程调用(RPC)框架,使用 Protocol Buffers 作为接口定义语言。 ```protobuf // 定义 .proto 文件 syntax = "proto3"; package helloworld; service Greeter { rpc SayHello (HelloRequest) returns (HelloResponse); } message HelloRequest { string name = 1; } message HelloResponse { string message = 1; } ``` ```java // 服务提供者 import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; import helloworld.GreeterGrpc.GreeterImplBase; import helloworld.HelloRequest; import helloworld.HelloResponse; import java.io.IOException; public class GrpcServer { private Server server; private void start() throws IOException { int port = 50051; server = ServerBuilder.forPort(port) .addService(new GreeterImpl()) .build() .start(); System.out.println("Server started, listening on " + port); Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.err.println("*** shutting down gRPC server since JVM is shutting down"); GrpcServer.this.stop(); System.err.println("*** server shut down"); })); } private void stop() { if (server != null) { server.shutdown(); } } private void blockUntilShutdown() throws InterruptedException { if (server != null) { server.awaitTermination(); } } static class GreeterImpl extends GreeterImplBase { @Override public void sayHello(HelloRequest req, StreamObserver<HelloResponse> responseObserver) { HelloResponse reply = HelloResponse.newBuilder().setMessage("Hello " + req.getName()).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } } public static void main(String[] args) throws IOException, InterruptedException { final GrpcServer server = new GrpcServer(); server.start(); server.blockUntilShutdown(); } } // 服务消费者 import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import helloworld.GreeterGrpc; import helloworld.HelloRequest; import helloworld.HelloResponse; public class GrpcClient { public static void main(String[] args) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051) .usePlaintext() .build(); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloRequest request = HelloRequest.newBuilder().setName("World").build(); HelloResponse response = stub.sayHello(request); System.out.println("Response: " + response.getMessage()); channel.shutdown(); } } ``` ### 异步通讯 - **消息队列(RabbitMQ)**:可实现微服务之间的异步通讯,解耦服务之间的依赖关系。 ```java // 消息生产者 import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; public class RabbitMQProducer { private final static String QUEUE_NAME = "hello"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); try (Connection connection = factory.newConnection(); Channel channel = connection.createChannel()) { channel.queueDeclare(QUEUE_NAME, false, false, false, null); String message = "Hello, RabbitMQ!"; channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8")); System.out.println(" [x] Sent &#39;" + message + "&#39;"); } } } // 消息消费者 import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class RabbitMQConsumer { private final static String QUEUE_NAME = "hello"; public static void main(String[] args) throws IOException, TimeoutException { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); channel.queueDeclare(QUEUE_NAME, false, false, false, null); System.out.println(" [*] Waiting for messages. To exit press CTRL+C"); DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody(), "UTF-8"); System.out.println(" [x] Received &#39;" + message + "&#39;"); }; channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { }); } } ``` - **Apache Kafka**:分布式流处理平台,适用于处理大规模的实时数据流。 ```java // 消息生产者 import org.apache.kafka.clients.producer.*; import java.util.Properties; public class KafkaProducerExample { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producer<String, String> producer = new KafkaProducer<>(props); ProducerRecord<String, String> record = new ProducerRecord<>("test_topic", "key", "value"); producer.send(record); producer.close(); } } // 消息消费者 import org.apache.kafka.clients.consumer.*; import java.time.Duration; import java.util.Collections; import java.util.Properties; public class KafkaConsumerExample { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "localhost:9092"); props.put("group.id", "test-group"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); consumer.subscribe(Collections.singletonList("test_topic")); while (true) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); for (ConsumerRecord<String, String> record : records) { System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value()); } } } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值