nacos依赖
<!--向Nacos注册自身信息-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!--配置中心,启动从注册中心下载yaml等配置文件覆盖本地application.yml-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
yml配置
新建一个bootstrap.yml与application.yml同级目录 bootstrap.yml内容:
spring:
application:
name: server-user
profiles:
active: dev #nacos的配置文件的后缀,可以是prod,dev等等不同运行环境的后缀
cloud:
nacos:
discovery:
server-addr: localhost:8848 #nacos注册地址
config:
server-addr: localhost:8848 #nacos拉取配置文件地址
file-extension: yaml #配置文件类型,可以是properties,yaml等
启动类注解
启动类加上注解 @EnableDiscoveryClient
刷新配置
@RefreshScope 用在需要读取yaml配置参数的类,只能刷新普通备至参数,不能使系统真实开放端口改变 比如 @Value("${server.port:1000}") 在nacos修改配置端口后,程序之前开放的端口依然不变,但是@Value注入的值会变
OpenFeign配置
依赖
<!--向Nacos注册自身信息-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
spring:
application:
name: server-user
启动类加上注解:@EnableFeignClients
@FeignClient("远程对应的服务名server-user")
public interface ServerFeign {
@GetMapping("/getUser")
Response getUser(@RequestParam("id") String id);
}
使用
@RestController
public class ServerController {
@Autowired
private ServerFeign serverFeign;
@GetMapping("/getUser")
public void getUser(String id,HttpServletResponse httpServletResponse) throws IOException {
httpServletResponse.setContentType("application/force-download");
try {
httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("a.txt", "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Response response = serverFeign.getUser(id);
InputStream inputStream = response.body().asInputStream();
ServletOutputStream outputStream = httpServletResponse.getOutputStream();
byte[] bytes=new byte[1024];
int len =0;
while ((len=(inputStream.read(bytes)))!=-1){
outputStream.write(bytes,0,len);
outputStream.flush();
}
}
|