Java之SpringCloud|Java之SpringCloud nocos注册中心讲解
一、nacos是什么?
Nacos是用来发现、配置和管理微服务。Nacos提供了一组简单易用的特性集,帮助快速实现动态服务发现、服务配置、服务元数据及流量管理。
二、使用步骤
1.安装nacos 服务器
直接运行 startup.cmd 访问 localhost:8848/nacos
初始密码 nacos nacos
文章图片
2.导入依赖和配置yaml
文章图片
父项目依赖pom文件
4.0.0 com.csdn springcloud_nacospom1.0-SNAPSHOT UTF-8 springcloud_share_6002 springcloud_user_6001 springcloud_common 1.8 1.8 4.12 1.18.16 1.2.17 1.2.3 8.0.21 1.1.23 2.1.4 2.3.8.RELEASEHoxton.SR92.2.3.RELEASE2.7.01.2.32.10.1 0.10.7 org.springframework.cloud spring-cloud-dependencies${spring-cloud-dependencies.version} pom importcom.alibaba.cloud spring-cloud-alibaba-dependencies${spring-cloud-alibaba.version} pom importorg.springframework.boot spring-boot-dependencies${spring-boot-dependencies.version} pom importmysql mysql-connector-java${mysql-connector-java.version} com.alibaba druid${druid.version} org.mybatis.spring.boot mybatis-spring-boot-starter${mybatis-spring-boot-starter.version} junit junit${junit.version} org.projectlombok lombok${lombok.version} log4j log4j${log4j.version} ch.qos.logback logback-core${logback-core.version} io.springfox springfox-swagger2${swagger.version} io.springfox springfox-swagger-ui${swagger.version} com.alibaba druid-spring-boot-starter${druid.version} com.github.pagehelper pagehelper-spring-boot-starter${pagehelper.version} joda-time joda-time${jodatime.version} io.jsonwebtoken jjwt-api${jjwt.version} io.jsonwebtoken jjwt-impl${jjwt.version} runtimeio.jsonwebtoken jjwt-jackson${jjwt.version} runtime
【Java之SpringCloud|Java之SpringCloud nocos注册中心讲解】在需要被nacos发现的微服务个module加上nacos依赖
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
springcloud_common的pom依赖
springcloud_nacoscom.csdn 1.0-SNAPSHOT 4.0.0 springcloud_commonorg.springframework.boot spring-boot-starter-weborg.projectlombok lombokio.springfox springfox-swagger2io.springfox springfox-swagger-uiorg.springframework.boot spring-boot-configuration-processortrue org.springframework.boot spring-boot-starter-amqpcom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discoverycom.alibaba.cloud spring-cloud-starter-alibaba-sentinelorg.springframework.cloud spring-cloud-starter-openfeignio.jsonwebtoken jjwt-apiio.jsonwebtoken jjwt-implruntimeio.jsonwebtoken jjwt-jacksonruntimeorg.springframework.cloud spring-cloud-starter-sleuthorg.springframework.cloud spring-cloud-starter-zipkinorg.projectlombok lombok
文章图片
@Configuration@EnableSwagger2public class Swagger2Config {/*** 定义接口的总体信息** @return*/private ApiInfo webApiInfo() {return new ApiInfoBuilder().title("Swagger API 文档").description("即使再小的帆也能远航").version("1.0").contact(new Contact("liar", "http://www.jsxllht.com", "**********6@qq.com")).build(); }private ApiInfo adminApiInfo() {return new ApiInfoBuilder().title("Swagger Admin 文档").description("即使再小的帆也能远航").version("1.0").contact(new Contact("liar", "http://www.jsxllht.com", "**********6@qq.co")).build(); }@Beanpublic Docket webApiConfig() {return new Docket(DocumentationType.SWAGGER_2).groupName("webApi") // 用户组.apiInfo(webApiInfo()) // 组的信息.select()//只显示api路径下的页面.paths(Predicates.and(PathSelectors.regex("/api/.*")))// 用户接口的判断.build(); }@Beanpublic Docket adminApiConfig() {return new Docket(DocumentationType.SWAGGER_2).groupName("adminApi") // 管路?组.apiInfo(adminApiInfo()) // 组的信息.select()//只显示admin路径下的页面.paths(Predicates.and(PathSelectors.regex("/admin/.*"))).build(); }}
/** *业务异常类 */@Data@NoArgsConstructor@AllArgsConstructor@Builderpublic class AppException extends RuntimeException{private String code; private String message; public AppException(ResponseEnum responseEnum){this.code = responseEnum.getCode(); this.message = responseEnum.getMessage(); }}
// 这是一个controller 的增强类【专门在controller 抛出异常的时候增强】@ControllerAdvicepublic class ControllerExceptionAdvice {/***如果抛出的是 AppException 的增强*返回值 就是返回的页面*参数: controller 抛出的异常*/@ExceptionHandler(AppException.class)@ResponseBodypublic R appExceptionHandler(AppException ex, HttpServletRequest request){return new R(ex.getCode(),ex.getMessage(),null); }/***如果抛出的是Exception 的增强*/@ExceptionHandler(Exception.class)@ResponseBodypublic R exceptionHandler(Exception ex, HttpServletRequest request){ex.printStackTrace(); return new R(ResponseEnum.SYSTEM_ERROR,null); }}
@Data@AllArgsConstructor@NoArgsConstructor@Builder// 创建统一的返回格式public class R{private String code; private String message; private T data; public R(ResponseEnum responseEnum, T data) {this.code = responseEnum.getCode(); this.message = responseEnum.getMessage(); this.data = https://www.it610.com/article/data; }}
public enum ResponseEnum {SUCCESS("200","成功003"),USERNAME_NOT_FOUND("300","用户名不存在"),USERNAME_OR_PASSWORD_INVALIDATE("301","用户名或者密码错误"),ROLE_NO_MENUS("302","此角色没有任何菜单权限,请尽早分配"),HAS_NO_TOKEN("303","还没有登录"),TOKEN_ERROR("304","别想试图伪造令牌"),TOKEN_TIMEOUT("305","对不起登录状态已经失效,请重新登录"),HAS_NO_RIGHT("306","权限不足"),SYSTEM_ERROR("500","发生未知异常。。。"),FEIGN_BSUY("307","系统正忙,稍后再试。。"),FLOW_BLOCK("308","流量被限制了,请稍后再使"),DEG_BLOCK("309","系统很忙,稍后再试。。。"),SMS_ERROR("310","短信发送失败,请稍后再试。。。"),SMS_SEND_ERROR_BUSINESS_LIMIT_CONTROL("311","发送短信太频繁,过会再发。。。"),CODE_ERROR("312","验证码错误请重试"),CODE_EXCPTION("313","验证码超时"),ACCOUNT_NO_EXISTS("314","用户不存在"),STATUS_BE_MODIFIED("315","用户已被审核"); private String code; private String message; public String getCode() {return code; }public void setCode(String code) {this.code = code; }public String getMessage() {return message; }public void setMessage(String message) {this.message = message; }ResponseEnum(String code, String message) {this.code = code; this.message = message; }}
springcloud_user_6001的yaml(在注册中心服务的名字 不能一样)
server:port: 6001#数据源spring:datasource:druid:url: jdbc:mysql://localhost:3306/hub_user_center?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMTdriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456initial-size: 10max-active: 50min-idle: 10max-wait: 60000pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20# mysql 数据库的特征会关闭已经连接了8个小时的连接validation-query: SELECT 1 FROM DUALapplication:name: user-6001cloud:nacos:discovery:server-addr: 127.0.0.1:8848# mybatis 配置mybatis:# 扫描映射文件mapper-locations: classpath:mapper/*.xmlconfiguration:# 开启驼峰映射配置map-underscore-to-camel-case: true# log# 整个工程只答应info 以及以上级别的日志logging:level:root: infocom.csqf.mapper: debug
springcloud_share_6002的yaml(在注册中心服务的名字 不能一样)
server:port: 6002#数据源spring:datasource:druid:url: jdbc:mysql://localhost:3306/hub_share_center?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMTdriver-class-name: com.mysql.cj.jdbc.Driverusername: rootpassword: 123456initial-size: 10max-active: 50min-idle: 10max-wait: 60000pool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20# mysql 数据库的特征会关闭已经连接了8个小时的连接validation-query: SELECT 1 FROM DUALapplication:name: share-6002cloud:nacos:discovery:server-addr: 127.0.0.1:8848# mybatis 配置mybatis:# 扫描映射文件mapper-locations: classpath:mapper/*.xmlconfiguration:# 开启驼峰映射配置map-underscore-to-camel-case: true# log# 整个工程只答应info 以及以上级别的日志logging:level:root: infocom.csqf.mapper: debug
2.RestTemplate
RestTemplate是Spring Resources中一个访问第三方RESTful API接口的网络请求框架。RestTemplate的设计原则和其他Spring Template(例如JdbcTemplate、JmsTemplate)类!,都是为执行复杂任务提供了一个具有默认行为的简单方法。
设置RestTemplate为Bean
文章图片
springcloud_user_6001中写一个查询方法代码如下(示例):
@Servicepublic class UserServiceImpl implements UserService {@Autowiredprivate UserMapper userMapper; @Overridepublic String getUserById(Integer id) {User user = userMapper.selectByPrimaryKey(id); if ("".equals(user)){return ""; }return user.getUserName(); }}
在springcloud_share_6002写一个DTO(示例):
继承Share实力类,加上user中返回的userName
@Datapublic class ShareDto extends Share {private String userName; }
在springcloud_share_6002中使用RestTemplate调用user并得到userName
@RestController@RequestMapping("/api/share")public class ShareContoller {@Autowiredprivate ShareServiceImpl shareService; @Autowiredprivate RestTemplate restTemplate; @GetMapping("/{id}")public R getShareById(@PathVariable("id") Integer id){Share share = shareService.getShareById(id); R r = restTemplate.getForObject("http://localhost:6001/api/user/" + share.getUserId(), R.class); String s = r.getData().toString(); ShareDto shareDto = new ShareDto(); BeanUtils.copyProperties(share,shareDto); shareDto.setUserName(s); return new R(ResponseEnum.SUCCESS,shareDto); }}
最后访问swagger(http://localhost:6002/swagger-ui.html)测试得到dto实体类中的对象
总结 nacos的作用就是一个注册中心,用来管理注册上来的各个微服务。
到此这篇关于Java之SpringCloud nocos注册中心讲解的文章就介绍到这了,更多相关Java之SpringCloud nocos内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- PMSJ寻平面设计师之现代(Hyundai)
- 太平之莲
- 闲杂“细雨”
- 七年之痒之后
- 深入理解Go之generate
- 由浅入深理解AOP
- 期刊|期刊 | 国内核心期刊之(北大核心)
- 生活随笔|好天气下的意外之喜
- 感恩之旅第75天