接下來使用Nacos作為服務註冊中心,一個服務的提供者,一個服務消費者。
環境:springboot2.2.10.RELEASE + nacos1.3.2
一、服務提供者
pom.mxl<properties> <java.version>1.8</java.version> <spring-cloud.version>Hoxton.SR1</spring-cloud.version> <spring-cloud-alibaba-dependencies.version>0.9.0.RELEASE</spring-cloud-alibaba-dependencies.version> <spring-cloud-alibaba.version>2.2.3.RELEASE</spring-cloud-alibaba.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${spring-cloud-alibaba.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
application.yml配置server: port: 9000---spring: application: name: nacos-provider---spring: cloud: nacos: username: dev password: 123123 discovery: enabled: true serverAddr: localhost:8848 namespace: 3d857485-5f81-4f1b-9a7e-86586d05261f
java相關類
1、啟動類添加註解@EnableDiscoveryClient
@SpringBootApplication@EnableDiscoveryClientpublic class NacosProviderApplication { public static void main(String[] args) { SpringApplication.run(NacosProviderApplication.class, args); }}
2、web測試介面
@RestController@RequestMapping("discovery")public class DiscoveryController { @NacosInjected private NamingService namingService; @Resource private DiscoveryClient discoverClient ; @GetMapping(value = "/get") public Object get(@RequestParam String serviceName) throws Exception { Map<String, Object> res = new HashMap<>() ; res.put("services", discoverClient.getServices()) ; res.put("instances", discoverClient.getInstances(serviceName)) ; res.put("port", 9000) ; return res ; }}
測試
啟動服務檢視nacos控制檯檢視服務是否註冊上來了
訪問測試介面:
到此服務提供者開發完成。
二、服務消費者
pom.xml與服務提供者一樣就不貼了。
application.yml配置:
server: port: 9100---spring: cloud: nacos: username: dev password: 123123 discovery: enabled: true serverAddr: localhost:8848 namespace: 3d857485-5f81-4f1b-9a7e-86586d05261f ---spring: application: name: nacos-consumer ---ribbon: eagerLoad: enabled: true
配置RestTemplate
@Configurationpublic class WebConfig { @LoadBalanced @Bean public RestTemplate restTemplate() { return new RestTemplate() ; } }
介面呼叫:
@RestController@RequestMapping("consumer")public class ConsumerController { @Resource private RestTemplate restTemplate ; @GetMapping("/get") public Object invoke(String serviceName) { return restTemplate.getForObject("http://nacos-provider/discovery/get?serviceName=" + serviceName, Object.class); } }
這裡直接透過服務名呼叫(nacos-provider)
啟動服務檢視Nacos
正常!
測試:
正常!
完畢!!!
最新評論