三、服务消费
发布时间:2020-12-16 23:42:02 所属栏目:百科 来源:网络整理
导读:1、代码演示 创建工程 我们在上一篇的基础上,再创建一个microservice-spring-cloud工程的子模块,将其命名为microservice-consumer-movie,并且在pom.xml文件中加入相关的依赖。 dependencies dependency groupId org.springframework.boot / groupId artif
1、代码演示创建工程我们在上一篇的基础上,再创建一个microservice-spring-cloud工程的子模块,将其命名为microservice-consumer-movie,并且在pom.xml文件中加入相关的依赖。 <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> 配置application.ymlspring:
application:
name: microservice-consumer-movie
server:
port: 3001
eureka:
client:
healthcheck:
enabled: true
serviceUrl:
defaultZone: http://admin:[email?protected]:1001/eureka
instance:
prefer-ip-address: true
instance-id: ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
应用主类创建应用主类。初始化RestTemplate,用来真正发起REST请求。@EnableEurekaClient注解用来将当前应用加入到服务治理体系中。 @SpringBootApplication @EnableEurekaClient public class MainAppConsumer { @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); } public static void main(String[] args) { SpringApplication.run(MainAppConsumer.class,args); } } 创建接口,消费microservice-provider-user提供的服务@RestController public class MovieController { @Autowired private RestTemplate restTemplate; @GetMapping("/movie/{id}") public User getById(@PathVariable("id") Long id){ return this.restTemplate.getForObject("http://localhost:2001/getUser/"+id,User.class); } } User实体类public class User implements Serializable { private Long id; private String username; private String name; private short age; private BigDecimal balance; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public short getAge() { return age; } public void setAge(short age) { this.age = age; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } } 我们先启动microservice-discovery-eureka,然后启动microservice-provider-user,最后启动microservice-consumer-movie,然后测试访问这个接口http://localhost:3001/movie/1,浏览器响应 {"id":1,"username":"user1","name":"张三","age":18,"balance":100.00} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |