学习Euraka的同学直接滑到最下面, 这里先为初学者介绍 RestTemplate.
平时我们使用 Http 工具发送请求通常都会有两个步骤, 先调用请求拿到响应信息, 再将响应信息通过 JSON 工具解析并转换为实体类. 总的来说, RestTemplate 是 spring 提供的一个用来模拟浏览器发送请求和接收响应的一个类, 它能基于 Http 协议实现远程调用. 但是需要注意的是, 它发送的是同步请求.
父工程依赖:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.4</version></parent>右键父工程创建新 maven 项目, 取名为 eurekademo.
项目引入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-test --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope></dependency><!-- https://mvnrepository.com/artifact/junit/junit --><dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope></dependency>EurekaDemoApplicationTest.java:
@SpringBootTestpublic class EurekaDemoApplicationTest { @Test public void testGet() { RestTemplate restTemplate = new RestTemplate(); //模拟浏览器的请求头, 很多国内免费的 api 都有这种限制, 一般我们会把以下配置请求头的代码写在一个拦截器中, 通过 restTemplate.setClientHttpRequestInitializers() 配置进去 HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"); HttpEntity<String> entity = new HttpEntity<>("parameters", headers); //节假日查询免费 api ResponseEntity<Holiday> forObject = restTemplate.exchange("http://timor.tech/api/holiday/info/2022-01-01", HttpMethod.GET, entity, Holiday.class); System.out.println(forObject.getBody()); /* //一般企业自己封装的接口不会对外开放, 所以不需要向上面那么麻烦, 下面的代码只是打个比方, 实际执行会报错 == start Holiday h1 = restTemplate.getForObject("http://timor.tech/api/holiday/info/2022-01-01", Holiday.class); Holiday h2 = restTemplate.postForObject("http://timor.tech/api/holiday/info/2022-01-01", null, Holiday.class); // == end */ }}作用: 管理项目集群而暴露的接口服务, 提供服务注册与发现的功能.
服务注册: 提供者 (暴露自己的服务给外部调用的角色) 向 Eureka 服务器注册自己.
服务发现: 消费者 (去调用暴露出来的服务的角色) 从 Eureka 服务器获取提供者的地址列表.
其中 Eureka 服务器也可以集群, 和其他 Eureka 服务器相互共享自己的资源.
接下来就开始搭建一个 Eureka 服务器.
父工程 pom 添加配置:
<properties> <spring.cloud.version>2021.0.1</spring.cloud.version></properties><dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring.cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement>eurekademo 项目中添加依赖:
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client --><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency>application.yml:
server: port: 8080spring: application: name: eureka-server# eureka服务器配置, 每个属性赋什么类型的值都可以按住 ctrl 点击属性名进去找到 set 操作eureka: client: service-url: defaultZone: http://localhost:8080/eureka #默认服务注册中心地址, 多个使用 ',' 隔开 register-with-eureka: false #是否注册, 默认值 true, 由于这个项目作为 eureka 的注册中心使用, 注册自己会报错, 配置其他注册中心地址不会报错 fetch-registry: false #是否检索服务, 默认值 true, 基本上这个项目不会去处理业务功能, 所以也不需要检索其他服务, 集群注册中心的话就赋 true server: eviction-interval-timer-in-ms: 10000 #注册中心清理无效节点的时间间隔, 默认为 60000L , 单位毫秒 ms创建启动类 EurekaDemoApplication , 注意组织名 groupId + .eurekademo 为启动类的父包, 我的 groupId 为 com.kent , 所以父包为 com.kent.eurekademo :
/** * @Title: EurekaDemoApplication * @Description: eureka 服务器注册中心 * @author: kent * @date: 2022/3/16 14:53 * @Version: 1.0 */@SpringBootApplication@EnableEurekaServer //boot 的特点就是需要 Enablepublic class EurekaDemoApplication { public static void main(String[] args) { SpringApplication.run(EurekaDemoApplication.class, args); }}ok , 直接 run 起来! 启动成功后访问 http://127.0.0.1:8080/ 就可以看到 eureka 展示的一些基本信息. 英文看不懂的话, 最好配备一个网易有道词典. ??

右键父工程创建新 maven 项目 consumerdemo
项目引入依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client --><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>application.yml 配置:
server: port: 15050spring: application: name: consumerdemo# 使用 eureka 暴露自身地址, 拉取其他服务地址eureka: client: fetch-registry: true register-with-eureka: true # fetch-registry 与 register-with-eureka 都为 true 表示即为提供者, 亦为消费者 service-url: defaultZone: http://127.0.0.1:8080/eureka eureka-server-connect-timeout-seconds: 10 # 连接注册中心超时时间, 默认 5, 单位秒, 一般和注册中心服务失效时间配置一致 eureka-server-read-timeout-seconds: 10 # 读取服务列表的超时时间, 默认 8, 单位秒 instance: #hostname: ${spring.application.name} # 主机名称, 作用于 eureka 管理页面服务实例列表的链接地址, 默认是自己电脑名, prefer-ip-address.instance.eureka=false 默认取这个 appname: ${spring.application.name} # 实例名称, 默认使用 spring.application.name 的值, 一般不配置 prefer-ip-address: true # 使用 ip 地址定义在注册中心的地址, 作用于 eureka 管理页面服务实例列表的链接地址, 默认为 false #ip-address: 127.0.0.1 # 主机 ip 地址, 基本上不配置, prefer-ip-address.instance.eureka=true 优先取这个 lease-renewal-interval-in-seconds: 5 # 服务续约间隔时间, 默认为 90, 单位秒创建启动类 ConsumerDemoApplication.java , 添加注解 @EnableEurekaClient, 那么启动起来这个提供者就开始生效了.
创建项目的过程以及配置都和提供者一样.
现在就是看看怎么调用, 创建一个前端控制器:
@RestControllerpublic class HelloEurekaController { @Autowired private DiscoveryClient discoveryClient; @Autowired private RestTemplate restTemplate; @GetMapping("testPort") public String testPort() { // 根据服务名获取实例列表 List<ServiceInstance> serviceInstances = discoveryClient.getInstances("consumerdemo"); ServiceInstance serviceInstance = serviceInstances.get(0); return "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort(); }}这里已经拿到提供者的访问地址, 该怎么调用我想应该难不倒你们??