一、maven配置
<groupId>com.wk.sc</groupId>
<artifactId>springcloud-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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-netflix-ribbon</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
二、application.yml配置
server:
port: 7070
spring:
application:
name: service-ribbon
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
三、启动类
@SpringBootApplication
@EnableEurekaClient //启用客户端发现配置
@EnableDiscoveryClient //启用DiscoveryClient实现
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceRibbonApplication.class, args);
}
@Bean //配置rest实例
@LoadBalanced //配置负载均衡
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
四、服务调用
/**
* 服务调用
*
*/
@Service
public class HelloService {
@Autowired
private RestTemplate restTemplate;
/**
* 服务调用
*
* @param name
* @return
*/
public String hiService(String name) {
return restTemplate.getForObject("http://service-hi/hi?name=" + name, String.class); //service-hi大小写不敏感
}
}
五、控制器调用服务
/**
* 服务调用模拟
*
*/
@RestController
public class HelloController {
@Autowired
private HelloService helloService;
@GetMapping(value = "/hi")
public String hi(@RequestParam String name) {
return helloService.hiService(name);
}
}
网友评论