java Nacos基础配置

java Nacos基础配置

  • springCloud学习记录
  • SpringCloud Alibaba Nacos(服务注册)
    • Nacos安装
  • 服务注册
    • 服务端
      • 父pom
      • pom
      • yml
      • 启动类
      • controller
    • 客户端
      • pom
      • yml
      • 启动类
      • 请求配置
      • controller

springCloud学习记录

SpringCloud Alibaba Nacos(服务注册)

相当于集成了Eureka+Config+Bus的解决方案

Nacos安装

1、下载并安装nacos(https://github.com/alibaba/nacos/releases)
windows下载zip;linux下载gz
2、解压后打开conf下application.properties,配置数据库中信息,配置文件为同目录的nacos-mysql.sql
在这里插入图片描述

3、修改bin目录下的startup.cmd文件,改为单机模式
java Nacos基础配置_第1张图片
4、执行startup.cmd
5、打开http://localhost:8848/nacos/,账号密码为nacos

服务注册

服务端

父pom

            
                com.alibaba.cloud
                spring-cloud-alibaba-dependencies
                2.1.0.RELEASE
                pom
                import
            

pom

        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-discovery
        

yml

server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # nacos地址

management:
  endpoints:
    web:
      exposure:
        include: "*"

启动类

@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9001 {
    public static void main(String[] args) {
        SpringApplication.run(PaymentMain9001.class, args);
    }
}

controller

@RestController
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;

    @GetMapping("/payment/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id){
        return "nacos register, serverport=" + serverPort + "\t id:" + id;
    }
}

客户端

pom

        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-discovery
        

yml

server:
  port: 83

spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848

#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
  nacos-user-service: http://nacos-payment-provider

启动类

@SpringBootApplication
@EnableDiscoveryClient
public class OrderNacosMain83 {
    public static void main(String[] args) {
        SpringApplication.run(OrderNacosMain83.class, args);
    }
}

请求配置

@Configuration
public class ApplicationContextConfig {

    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}

controller

@RestController
@Slf4j
public class OrderNacosController {

    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serverUrl;

    @GetMapping("/consumer/payment/nacos/{id}")
    public String paymentInfo(@PathVariable("id") Integer id){
        return restTemplate.getForObject(serverUrl + "/payment/nacos/" + id, String.class);
    }
}

你可能感兴趣的:(spring,cloud,java,spring,cloud,开发语言)