Nepxion Discovery学习笔记1 Nacos注册中心服务器+Feign伪Http客户端

目录

Nacos是阿里巴巴开发的一个开源服务器,使用前先下载安装好Nacos,并启动服务,才能正常使用和访问注册中心!

笔记1:

Nacos的作用就是一个注册中心:

笔记2:

Feign是Spring Cloud提供的一个声明式的伪Http客户端:


Nacos是阿里巴巴开发的一个开源服务器,使用前先下载安装好Nacos,并启动服务,才能正常使用和访问注册中心:

下载后解压双击startup.cmd启动nacos服务:

启动成功:

访问本地Nacos服务地址: http://localhost:8848/nacos (注意:首次登陆应该会需要输入账号密码: 账号密码都是: nacos ) 即可看见:

笔记1:

Nacos的作用就是一个注册中心:

依赖:

<!--nacos客户端-->
<dependency>
   <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

1.在启动类中添加 @EnableDiscoveryClient 注解 //开启服务注册发现功能 :该注解自动注册了DiscoveryClient对象,可以把该服务注册到Nacos注册中心中去,从而实现服务注册和发现!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableFeignClients//启动Fegin支持
@EntityScan(basePackages = {"com.stephen.shopcommon"})
@SpringBootApplication
public class OrderApplication {

	public static void main(String[] args) {
		SpringApplication.run(OrderApplication.class, args);
	}

	@Bean
	@LoadBalanced //该注解可以利用springcloud继承的Ribbon工具实现自动化负载均衡
	public RestTemplate restTemplate() { return new RestTemplate(); }
}

2.Controller层中注入DiscoveryClient,就可以调用方法获取服务了:

package com.stephen.shoporder.controller;

import com.alibaba.fastjson.JSON;
import com.stephen.shopcommon.model.Order;
import com.stephen.shopcommon.model.Product;
import com.stephen.shoporder.service.Feign.ProductService;
import com.stephen.shoporder.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;


@RestController
@Slf4j
public class OrderController {
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private OrderService orderService;

	/*
	DiscoveryClient是专门负责服务注册和发现的,我们可以通过它获取到注册到注册中心的所有服务
	当启动类添加了@EnableDiscoveryClient注解后,就会直接注册DiscoveryClient,因此这里可以直接注入
	 */
	@Autowired
	private DiscoveryClient discoveryClient;

	//准备买1件商品
	@GetMapping("/order/prod/{pid}")
	public Order order(@PathVariable("pid") Integer pid) {
		log.info(">>客户下单,这时候要调用商品微服务查询商品信息");

		//从nacos中获取服务地址:
//      discoveryClient.getInstances("").get(0):获取名为 service-product 的微服务的实例集合的第一个服务对象(ServiceInstance对象)
		List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
//		通过随机挑选端口来实现负载均衡
//		new Random().nextInt(instances.size()):随机产生一个区间在 [0,instances长度) 的正整数
		ServiceInstance serviceInstance = instances.get(new Random().nextInt(instances.size()));

		//获取服务对象的地址和端口号组成的字符串
		String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
		log.info(">>从nacos中获取到的微服务地址为:" + url);

		//通过restTemplate调用获取到的服务对象的接口
		Product product = restTemplate.getForObject("http://" + url + "/product/" + pid, Product.class);
		log.info(">>商品信息,查询结果:" + JSON.toJSONString(product));

		Order order = new Order();
		order.setOid(8L);
		order.setUid(1);
		order.setUsername("测试用户");
		order.setPid(product.getPid());
		order.setPname(product.getPname());
		order.setPprice(product.getPprice());
		order.setNumber(1);
		orderService.save(order);
		return order;
	}

}

笔记2:

FeignSpring Cloud提供的一个声明式的伪Http客户端:

依赖:
<!--fegin组件--> 
<dependency> 
    <groupId>org.springframework.cloud</groupId> 
    <artifactId>spring-cloud-starter-openfeign</artifactId> 
</dependency>

1.Feign默认集成了 Ribbon,Nacos很好的兼容了Feign, 所以在Nacos下使用Fegin默认就实现了负 载均衡的效果。

2.在启动类中添加 @EnableFeignClients 注解 //开启Fegin功能 :就可以允许调用Nacos中心已注册服务的接口了.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableFeignClients//启动Fegin支持
@EnableDiscoveryClient//启动DiscoveryClient支持(用于服务注册和发现,可获取到注册中心的所有服务)
@EntityScan(basePackages = {"com.stephen.shopcommon"})
@SpringBootApplication
public class OrderApplication {

	public static void main(String[] args) {
		SpringApplication.run(OrderApplication.class, args);
	}

	@Bean
	@LoadBalanced //该注解可以利用springcloud继承的Ribbon工具实现自动化负载均衡
	public RestTemplate restTemplate() { return new RestTemplate(); }
}

3.使用Feign需要创建一个 interface接口类 并添加 @FeignClient("被调用的微服务名")注解 ,再如Controller层写接口一样去编写接口即可实现其他微服务接口的调用了。

@FeignClient("service-product")
//声明调用的提供者的name
public interface ProductService {
	//指定调用提供者的哪个方法
	// @FeignClient+@GetMapping 就是一个完整的请求路径 http://service- product/product/{pid}
	@GetMapping(value = "/product/{pid}")
	Product findByPid(@PathVariable("pid") Integer pid);
}

4.Controller层注入接口类,并调用接口方法即可.

		//通过Fegin调用商品微服务
		Product product = productService.findByPid(pid);

猜你喜欢

转载自blog.csdn.net/weixin_42585386/article/details/109216795