一、创建此spring cloud 项目一共有四个模块,包括公用资源模块,eureka注册中心模块,提供者模块和消费者模块
本人也是刚开始学习spring cloud,写了此笔记,大家耐心看一下,我们共同学习,有不足的地方欢迎各位大佬指正
启动效果如下
这里是RunDashboard,如果启动过程没有启动,请看这个链接,教大家如何启动
Run Dashboard 设置参考链接
UTF-8
1.8
1.8
4.12
1.16.18
1.2.17
5.1.47
1.1.16
1.3.0
org.springframework.boot
spring-boot-dependencies
2.2.2.RELEASE
pom
import
org.springframework.cloud
spring-cloud-dependencies
Hoxton.SR1
pom
import
com.alibaba.cloud
spring-cloud-alibaba-dependencies
2.1.0.RELEASE
pom
import
mysql
mysql-connector-java
${mysql.version}
runtime
com.alibaba
druid
${druid.version}
org.mybatis.spring.boot
mybatis-spring-boot-starter
${mybatis.spring.boot.version}
junit
junit
${junit.version}
log4j
log4j
${log4j.version}
2、新建子Module 创建service层 接口
public interface PaymentService {
public int create(Payment payment);
public Payment getPaymentById(@Param("id") Long id);
}
创建接口实现类
@Service
public class PaymentServiceImpl implements PaymentService {
@Resource
private PaymentDao paymentDao;
public int create(Payment payment){
return paymentDao.create(payment);
}
public Payment getPaymentById(Long id){
return paymentDao.getPaymentById(id);
}
}
然后创建Controller层PaymentController类
@RestController
@Slf4j
public class PaymentController {
@Autowired
private PaymentService paymentService;
@Value("${server.port}")
private String serverPort;
@Autowired
private DiscoveryClient discoveryClient;
@PostMapping(value = "/payment/create")
public CommonResult create( @RequestBody Payment payment){
int result = paymentService.create(payment);
log.info("****结果"+result);
if(result > 0){
return new CommonResult(200,"插入数据成功,serverPort"+serverPort,result);
}
else {
return new CommonResult(444,"插入数据失败",null);
}
}
@GetMapping (value = "/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
Payment result = paymentService.getPaymentById(id);
log.info("****结果"+result);
if(result != null){
return new CommonResult(200,"查询数据成功,serverPort"+serverPort,result);
}
else {
return new CommonResult(444,"没有对应记录,查询ID:"+id,null);
}
}
@GetMapping(value = "/payment/discovery")
public Object discovery(){
List services = discoveryClient.getServices();
for(String s :services){
log.info("**********element"+s);
}
List instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
// System.out.println(instances.get(0)+"/t"+instances.get(1));
for (ServiceInstance instance : instances) {
log.info(instance.getServiceId()+"/t"+instance.getHost()+"/t"+instance.getPort()+"/t"+instance.getUri());
}
return this.discoveryClient;
}
}
到此为止就创建好了提供者,然后我们要先运行注册中心启动类,然后再运行提供者启动类
启动之后打开浏览器输入:localhost:7001 可以看到有这个服务显示就说明已经注册到注册中心了
原创文章 3获赞 8访问量 421
关注
私信
展开阅读全文
作者:Ergou233