springcloud服务消费端之从消费端直接到服务提供端-03
springcloud入门详细搭建微服务环境-01
springcloud服务提供端-02
springcloud消费端是在以上的基础上搭建的:
1.导入依赖的jar包
<!-- springBoot支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot 测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- Eureka 客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- spring cloud 核心,自动配置 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2.写一个消费服务端的入口类
package cn.mesmile;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Created with IDEA
* @author: Super Zheng
* @Description: java类作用描述
* @Date:2019/1/6
* @Time:14:11
这里演示 直接从 消费端到服务提供端
*/
@SpringBootApplication
public class UserConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(UserConsumerApplication.class);
}
}
3.写一个config类
package cn.mesmile.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* @Created with IDEA
* @author: Super Zheng
* @Description: java类作用描述
* @Date:2019/1/6
* @Time:14:15
*/
@Configuration
public class ConfigBean {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
4.写一个消费端controller类
package cn.mesmile.controller;
import cn.mesmile.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @Created with IDEA
* @author: Super Zheng
* @Description: java类作用描述
* @Date:2019/1/6
* @Time:14:12
*/
@RestController
@RequestMapping("/consumer")
public class UserController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping("/user/{id}")
public User getUser(@PathVariable(name = "id") Long id){
String url = "http://localhost:8001/provider/user/"+id;
return restTemplate.getForObject(url, User.class);
}
}
5.写配置文件
server:
port: 9001
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka #告诉服务提供者要把服务注册到哪里
instance:
prefer-ip-address: true #显示客户端ip
spring:
application:
name: USER-CONSUMER #不要使用下划线
还没有评论,来说两句吧...