一、nacos是什么?
Nacos是用来发现、配置和管理微服务。Nacos提供了一组简单易用的特性集,帮助快速实现动态服务发现、服务配置、服务元数据及流量管理。
二、使用步骤
1.安装nacos 服务器
直接运行 startup.cmd 访问 localhost:8848/nacos
初始密码 nacos nacos
2.导入依赖和配置yaml
父项目依赖pom文件
4.0.0 com.csdn springcloud_nacos pom 1.0-SNAPSHOT springcloud_share_6002 springcloud_user_6001 springcloud_common UTF-8 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.RELEASE Hoxton.SR9 2.2.3.RELEASE 2.7.0 1.2.3 2.10.1 0.10.7 org.springframework.cloud spring-cloud-dependencies ${spring-cloud-dependencies.version} pom import com.alibaba.cloud spring-cloud-alibaba-dependencies ${spring-cloud-alibaba.version} pom import org.springframework.boot spring-boot-dependencies ${spring-boot-dependencies.version} pom import mysql 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} runtime io.jsonwebtoken jjwt-jackson ${jjwt.version} runtime
在需要被nacos发现的微服务个module加上nacos依赖
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery
springcloud_common的pom依赖
springcloud_nacos com.csdn 1.0-SNAPSHOT 4.0.0 springcloud_common org.springframework.boot spring-boot-starter-web org.projectlombok lombok io.springfox springfox-swagger2 io.springfox springfox-swagger-ui org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-starter-amqp com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery com.alibaba.cloud spring-cloud-starter-alibaba-sentinel org.springframework.cloud spring-cloud-starter-openfeign io.jsonwebtoken jjwt-api io.jsonwebtoken jjwt-impl runtime io.jsonwebtoken jjwt-jackson runtime org.springframework.cloud spring-cloud-starter-sleuth org.springframework.cloud spring-cloud-starter-zipkin org.projectlombok lombok
@Configuration @EnableSwagger2 public class Swagger2Config { /** * 定义接口的总体信息 * * @return */ private ApiInfo webApiInfo() { return new ApiInfoBuilder() .title("Swagger API 文档") .description("即使再小的帆也能远航") .version("1.0") .contact(new Contact("liar", "http://www.jsxllht.com", "**********[email protected]")) .build(); } private ApiInfo adminApiInfo() { return new ApiInfoBuilder() .title("Swagger Admin 文档") .description("即使再小的帆也能远航") .version("1.0") .contact(new Contact("liar", "http://www.jsxllht.com", "**********[email protected]")) .build(); } @Bean public Docket webApiConfig() { return new Docket(DocumentationType.SWAGGER_2) .groupName("webApi") // 用户组 .apiInfo(webApiInfo()) // 组的信息 .select() //只显示api路径下的页面 .paths(Predicates.and(PathSelectors.regex("/api/.*"))) // 用户接口的判断 .build(); } @Bean public Docket adminApiConfig() { return new Docket(DocumentationType.SWAGGER_2) .groupName("adminApi") // 管路⚪组 .apiInfo(adminApiInfo()) // 组的信息 .select() //只显示admin路径下的页面 .paths(Predicates.and(PathSelectors.regex("/admin/.*"))) .build(); } }
/** * 业务异常类 */ @Data @NoArgsConstructor @AllArgsConstructor @Builder public class AppException extends RuntimeException{ private String code; private String message; public AppException(ResponseEnum responseEnum){ this.code = responseEnum.getCode(); this.message = responseEnum.getMessage(); } }
// 这是一个controller 的增强类【专门在controller 抛出异常的时候 增强】 @ControllerAdvice public class ControllerExceptionAdvice { /** * 如果抛出的是 AppException 的增强 * 返回值 就是返回的页面 * 参数: controller 抛出的异常 */ @ExceptionHandler(AppException.class) @ResponseBody public R appExceptionHandler(AppException ex, HttpServletRequest request){ return new R(ex.getCode(),ex.getMessage(),null); } /** * 如果抛出的是Exception 的增强 */ @ExceptionHandler(Exception.class) @ResponseBody public 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 = 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=GMT driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 initial-size: 10 max-active: 50 min-idle: 10 max-wait: 60000 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 # mysql 数据库的特征 会关闭已经连接了8个小时的连接 validation-query: SELECT 1 FROM DUAL application: name: user-6001 cloud: nacos: discovery: server-addr: 127.0.0.1:8848 # mybatis 配置 mybatis: # 扫描映射文件 mapper-locations: classpath:mapper/*.xml configuration: # 开启驼峰映射配置 map-underscore-to-camel-case: true # log # 整个工程只答应info 以及以上级别的日志 logging: level: root: info com.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=GMT driver-class-name: com.mysql.cj.jdbc.Driver username: root password: 123456 initial-size: 10 max-active: 50 min-idle: 10 max-wait: 60000 pool-prepared-statements: true max-pool-prepared-statement-per-connection-size: 20 # mysql 数据库的特征 会关闭已经连接了8个小时的连接 validation-query: SELECT 1 FROM DUAL application: name: share-6002 cloud: nacos: discovery: server-addr: 127.0.0.1:8848 # mybatis 配置 mybatis: # 扫描映射文件 mapper-locations: classpath:mapper/*.xml configuration: # 开启驼峰映射配置 map-underscore-to-camel-case: true # log # 整个工程只答应info 以及以上级别的日志 logging: level: root: info com.csqf.mapper: debug
2.RestTemplate
RestTemplate是Spring Resources中一个访问第三方RESTful API接口的网络请求框架。RestTemplate的设计原则和其他Spring Template(例如JdbcTemplate、JmsTemplate)类!,都是为执行复杂任务提供了一个具有默认行为的简单方法。
设置RestTemplate为Bean
springcloud_user_6001中写一个查询方法代码如下(示例):
@Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public String getUserById(Integer id) { User user = userMapper.selectByPrimaryKey(id); if ("".equals(user)){ return ""; } return user.getUserName(); } }
在springcloud_share_6002写一个DTO(示例):
继承Share实力类,加上user中返回的userName
@Data public class ShareDto extends Share { private String userName; }
在springcloud_share_6002中使用RestTemplate调用user并得到userName
@RestController @RequestMapping("/api/share") public class ShareContoller { @Autowired private ShareServiceImpl shareService; @Autowired private 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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!