【sprinb-boot】改造成 spring-cloud 项目

改造过程

添加依赖

在 POM (pom.xml) 中添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>xxx</groupId>
	<artifactId>xxx</artifactId>
	<version>1.0</version>
	<packaging>jar</packaging>

	<name>xxx</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		...
		<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
	</properties>

	<dependencies>
		...
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-openfeign</artifactId>
		</dependency>
		...
	</dependencies>

	<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>
	...
</project>

启用 Spring Cloud 能力

在 Application 类中添加 @EnableEurekaClient、@EnableDiscoveryClient 和 @EnableFeignClients,如下:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class Application {

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

连入 Eureka Server

在 application.properties 中添加配置:

# 为服务指定个名字
spring.application.name=microservice-hello

#eureka client configuration
eureka.client.serviceUrl.defaultZone=http://localhost:12000/eureka/

# 调用者添加如下配置,可以避免异常:Read timed out
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=6000
spring.cloud.loadbalancer.retry.enabled=true
ribbon.ReadTimeout=60000
ribbon.ConnectTimeout=60000

异常:Read timed out

添加服务

略。

调用服务

略。

posted @ 2024-06-27 10:39  CharyGao  阅读(36)  评论(0)    收藏  举报