controller
package com.yanghongzhou.nacos.controller;
import java.net.URI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping("/nacos")
public class NacosTestController {
@Autowired
RestTemplate restTemplate;
@Value("${server.port}")
String port;
@RequestMapping("/test")
public String test() throws Exception {
System.out.println("laile," + port);
// URI url = new URI("http://10.1.2.106:8088/cmp/nacos/testService");
URI url = new URI("http://nacos-test-service/nacos/testService");
String msg = restTemplate.getForObject(url, String.class);
return "可不是直接访问:" + msg;
}
@RequestMapping("/testService")
public String testService() throws Exception {
return "hello nacos!" + port;
}
}
如上,test通过服务名调testService,testService可以在另一个工程中
浏览器测试
第二,整合dubbo,目的是controller可以访问servicecontroller及service
package com.yanghongzhou.nacos.controller;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yanghongzhou.nacos.dubbo.service.DubboTestService;
@RestController
@RequestMapping("/dubbo")
public class DubboTestController {
@DubboReference
private DubboTestService dubboTestService;
@RequestMapping("/test")
public String testDubbo() {
return dubboTestService.testDubbo();
}
}
package com.yanghongzhou.nacos.dubbo.service;
import org.apache.dubbo.config.annotation.DubboService;
@DubboService
public class DubboTestServiceImpl implements DubboTestService{
@Override
public String testDubbo() {
return "这是rpc的dubbo远程service访问";
}
}
很简单,两个注解,controller用 @DubboReference,service用@DubboService
浏览器测试
第三,依赖1,application.yml
server:
port: 8088
spring:
application:
name: nacos-test-service
cloud:
nacos:
server-addr: 10.1.2.106:8848
discovery:
username: nacos
password: nacos
namespace: public
dubbo:
application:
name: dubbo-test-service
registry:
address: nacos://10.1.2.106:8848
username: nacos
password: nacos
scan:
base-packages: com.yanghongzhou.nacos.dubbo.service
protocol:
name: dubbo
port: 15511
2,pom.xml 注意版本
第四,说明4.0.0 nacos-test nacos-test0.0.1-SNAPSHOT org.springframework.boot spring-boot-starter-web2.4.2 com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery2021.1 org.springframework.cloud spring-cloud-starter-loadbalancer3.0.1 org.yaml snakeyaml1.30 org.springframework spring-context5.3.3 org.apache.dubbo dubbo-spring-boot-starter2.7.11 org.apache.dubbo dubbo2.7.11 org.apache.dubbo dubbo-registry-nacos2.7.11
我为了方便,将两个功能的样例都放在一个工程中了,实际是分开的,不过这都不重要。
付nacos管理截图



