SpringCloud整合Nacos(2.服务注册)
1.服务提供者模块
1.1 新建bootstrap.yml启动配置
server: port: 9001 spring: application: name: module-abc #作为服务feign的value profiles: active: dev cloud: nacos: discovery: server-addr: 127.0.0.1:8848
1.2 新建服务提供者逻辑:
@RestController @RequestMapping("/sample") public class SampleController{ @GetMapping(value="/label") public String getLabel(@RequestParam("id") Integer id) { return id==0?"zero":"nonZero"; } }
此时可以启动该服务,测试api的正确性
2.服务消费者模块
2.1新建消费者服务接口
@FeignClient("module-abc") // 此处的module-abc即为服务提供者的模块名 @RequestMapping(value="/sample") public interface ISampleController { @GetMapping(value = "/label") String getLabel(@RequestParam("id") Integer id); }
2.2新建bootstrap.yml启动配置
spring: application: name: main profiles: active: dev cloud: nacos: discovery: server-addr: 127.0.0.1:8848
2.3 修改消费者启动文件
添加 @EnableFeignClients 注解,同时指定接口发现的报地址 basePackages = "com.zhiscity.framework.users.microapi"
@EnableDiscoveryClient @SpringBootApplication @EnableFeignClients(basePackages = "com.zhiscity.framework.users.microapi")//此处要指定服务接口的包地址 @EnableHystrixDashboard//开启断路器监控 @EnableCircuitBreaker//开启断路器监 @EnableTransactionManagement @ServletComponentScan @MapperScan(basePackages = "com.zhiscity.framework.users.dao") public class UsersApplication { private static final Logger logger = LoggerFactory.getLogger(UsersApplication.class); public static void main(String[] args) { logger.info("\r\n=====================服务启动start====================="); SpringApplication.run(UsersApplication.class, args); logger.info("\r\n=====================服务启动end====================="); } }
2.4 通过接口调用服务
@RestController @RequestMapping("/users") public class Usercontroller { @Resource private ISampleController sampleController; @RequestMapping("/{id}") public String text(@PathVariable Integer id) { return sampleController.getLabel(id); } }
通过以上的配置后,可以测试服务注册和使用