在pom文件的依赖管理中加入 spring cloud alibaba 的依赖管理 这样引入相关依赖的时候就不用加版本了;
<dependencyManagement>
<dependencies>
<!-- 定义 spring cloud alibaba-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba-dependencies.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!--nacos服务注册与发现-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
在启动类上加 @EnableDiscoveryClient
注解
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class);
}
}
在application.yml 下加配置
spring:
application:
name: demo-service
cloud:
nacos:
server-addr: localhost:8848
统一配置
命名空间:区分开发、测试和生产环境,环境配置隔离
dateId: a p p l i c a t i o n . n a m e − {application.name}- application.name−{profile}.${file-extension}
group:做同一个环境中的不同服务分组,不同业务配置隔离
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-config</artifactId>
</dependency>
bootstrap.yml文件是引导文件,比application.yml先加载
spring:
cloud:
nacos:
config:
server-addr: localhost:8848
namespace: ee9a7297-5785-4396-8568-3e2d390fa979
group: java-demo
file-extension: yaml
refresh-enabled: true
discovery:
server-addr: localhost:8848
namespace: ee9a7297-5785-4396-8568-3e2d390fa979
group: java-demo
application:
name: demo-provider
nacos的配置是会覆盖本地配置的
<!-- open feign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
@EnableFeignClients
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class);
}
}
@FeignClient("demo-provider") //告诉spring cloud这个接口是一个远程客户端,要调用demo-provider服务(nacos中找到),具体是调demo-provider服务的/demo/provider/getUser对应的方法
public interface UserFeignService {
// 远程服务的url
@RequestMapping("/demo/provider/getUser")//注意写全优惠券类上还有映射//注意我们这个地方不是控制层,所以这个请求映射请求的不是我们服务器上的东西,而是nacos注册中心的
CommonResponse<Object> getUser();;//得到一个CommonResponse对象
}
@RestController
@RequestMapping("demo/order")
public class OrderController {
@Autowired
private UserFeignService feignService;
@RequestMapping("/feign")
public CommonResponse<Object> feign(){
return CommonResponse.success(feignService.getUser(), "success");
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- haog.cn 版权所有 赣ICP备2024042798号-2
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务