同一项目启动多个实例
pom.xml
勾选Allow parallel run
运行实例之后换一个端口再运行就能创建多个实例
ribbon
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.com</groupId>
<artifactId>rib</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>rib</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR5</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
yml文件与服务端类似
spring:
application:
name: rib
server:
port: 8764
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8081/eureka/
RibApplication
加上@EnableDiscoveryClient
@SpringBootApplication
@EnableDiscoveryClient
public class RibApplication {
public static void main(String[] args) {
SpringApplication.run(RibApplication.class, args);
}
}
创建config包
下创建RestTemplateConfiguration
@Configuration
public class RestTemplateConfiguration {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
创建service
用服务端的spring-application-name访问
@Service
public class ClientService {
@Autowired
private RestTemplate restTemplate;
public String sayHi(String message) {
System.out.println(message);
//client是服务的spring-application-name
return restTemplate.getForObject("http://client/hi?message="+message,String.class);
}
}
创建controller
@RestController
public class RibController {
@Autowired
private ClientService clientService;
@RequestMapping(value = "hi",method = RequestMethod.GET)
public String sayHi(String message) {
return clientService.sayHi(message);
}
}