案例项目:案例项目
码云自取,别整什么积分了!
- 启动Nacos
- 父(模块)
- 实体类(模块)
- 提供者(模块)
- 消费者(模块)
- 启动与测试
百度都有
父模块用Spring Initializr
就一个实体类,提供者和消费者都会用到
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student {
private String name;
private Integer age;
}
提供者模块
依赖实体类模块
启动类
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ProviderApp {
public static void main(String[] args) {
SpringApplication.run(ProviderApp.class, args);
}
@GetMapping("/student/1")
public Student fun1() {
System.out.println("/student/1");
return new Student("小明", 23);
}
}
配置文件
spring:
application:
name: provider # 服务名
cloud:
nacos:
discovery: # 注册中心地址
server-addr: localhost:8848
username: nacos
password: nacos
server:
port: 9001 # 服务端口
测试
运行提供者,访问URL:http://localhost:9001/student/1
成功!
依赖实体类模块
启动类
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ConsumerApp {
public static void main(String[] args) {
SpringApplication.run(ConsumerApp.class, args);
}
@Bean
@LoadBalanced
public RestTemplate initRT() {
return new RestTemplate();
}
@Autowired
private RestTemplate rt;
@GetMapping("/query")
public Student fun1() {
Student student = rt.getForObject("http://provider/student/1", Student.class);
System.out.println("/query");
System.out.println(student);
return student;
}
}
配置文件
spring:
application:
name: consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
username: nacos
password: nacos
server:
port: 9002
启动
运行消费者,访问URL:http://localhost:9002/query
成功!



