From 53834ff5e1fff5b8ffbbd903101640646ff510ad Mon Sep 17 00:00:00 2001 From: yeqd Date: Thu, 26 Nov 2020 10:15:25 +0800 Subject: [PATCH 1/3] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E8=A7=A3=E5=86=B3swagger?= =?UTF-8?q?=E6=97=A0=E6=95=88=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- user-service/pom.xml | 2 ++ .../com/hp/user/service/UserServiceApplaction.java | 12 ++++++++---- .../com/hp/user/service/config/SwaggerConfig.java | 11 ++++++----- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/user-service/pom.xml b/user-service/pom.xml index d7ba613..ca69cbf 100644 --- a/user-service/pom.xml +++ b/user-service/pom.xml @@ -49,6 +49,8 @@ spring-boot-starter-json org.springframework.boot + + org.springframework spring-beans diff --git a/user-service/src/main/java/com/hp/user/service/UserServiceApplaction.java b/user-service/src/main/java/com/hp/user/service/UserServiceApplaction.java index 8195550..56e411c 100644 --- a/user-service/src/main/java/com/hp/user/service/UserServiceApplaction.java +++ b/user-service/src/main/java/com/hp/user/service/UserServiceApplaction.java @@ -1,12 +1,12 @@ package com.hp.user.service; -import cn.nyhlw.doc2swagger.springswagger2.EnableSwagger2; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.ComponentScan; import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource; -import org.springframework.context.annotation.ComponentScan; /** * 用户服务启动类 @@ -14,11 +14,15 @@ import org.springframework.context.annotation.ComponentScan; * @since 2020/11/18 * */ -@EnableSwagger2 @MapperScan("com.hp.user.service.dao") //扫描的mapper @SpringBootApplication @NacosPropertySource(dataId = "userdatasource", autoRefreshed = true) -@ComponentScan("com.hp.user.service.config") +//不能加compentscan,加了 +@ComponentScan("com.hp.user.service.dao")//这个地方不能写错,写错的话会出现2个问题,如果写的路径扫描不到swaggerconfig那么页面会报错 +//(Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. +//The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually: ), +//如果写的路径扫描不到controller那么页面不会有接口信息 +//所以最好不要写 public class UserServiceApplaction { public static void main(String[] args) { SpringApplication.run(UserServiceApplaction.class, args); diff --git a/user-service/src/main/java/com/hp/user/service/config/SwaggerConfig.java b/user-service/src/main/java/com/hp/user/service/config/SwaggerConfig.java index a6b2b85..f7602c1 100644 --- a/user-service/src/main/java/com/hp/user/service/config/SwaggerConfig.java +++ b/user-service/src/main/java/com/hp/user/service/config/SwaggerConfig.java @@ -1,21 +1,22 @@ package com.hp.user.service.config; -import java.util.Arrays; - -import cn.nyhlw.doc2swagger.springswagger2.EnableSwagger2; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import cn.nyhlw.doc2swagger.core.config.RestDocConfig; +//import cn.nyhlw.doc2swagger.springswagger2.EnableSwagger2; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; +//这两个注释一定要有,没有以及EnableSwagger2依赖错误会报 +//(Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. +//The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually: ), @Configuration -@EnableSwagger2 +@EnableSwagger2//并且这个注释要特别注意不能使用cn.nyhlw.doc2swagger.springswagger2.EnableSwagger2;一定要使用springfox.documentation.swagger2.annotations.EnableSwagger2; public class SwaggerConfig { public static final String VERSION = "1.0.0"; public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.hp.user.service.controller"; From 02f70a9204c628f542d7c6ba9a0ba3bfb5f9b8e4 Mon Sep 17 00:00:00 2001 From: yeqd Date: Thu, 26 Nov 2020 10:17:11 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/service/config/SwaggerConfig1.java | 136 ------------------ 1 file changed, 136 deletions(-) delete mode 100644 user-service/src/main/java/com/hp/user/service/config/SwaggerConfig1.java diff --git a/user-service/src/main/java/com/hp/user/service/config/SwaggerConfig1.java b/user-service/src/main/java/com/hp/user/service/config/SwaggerConfig1.java deleted file mode 100644 index 142552e..0000000 --- a/user-service/src/main/java/com/hp/user/service/config/SwaggerConfig1.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.hp.user.service.config; - -import org.springframework.context.annotation.Bean; - -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - - -@Configuration -@EnableSwagger2 -public class SwaggerConfig1{ - - - /** - * 创建API应用 - * apiInfo() 增加API相关信息 - * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现, - * 本例采用指定扫描的包路径来定义指定要建立API的目录。 - * - * @return - */ - @Bean - public Docket createRestApi() { - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.hp.user.service.controller")) - .paths(PathSelectors.any()) - .build(); - } - - /** - * 创建该API的基本信息(这些基本信息会展现在文档页面中) - * 访问地址:http://项目实际地址/swagger-ui.html - * @return - */ - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("Spring Boot中使用Swagger2构建RESTful APIs") - .version("1.0") - .build(); - } -// public static final String VERSION = "1.0.0"; -// public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.hp.user.service.controller"; -// -// -// -// @Bean -// public Docket createRestApi() { -// return new Docket(DocumentationType.SWAGGER_2) -// .select() -// /*此处为你的访问层接口包路径,即控制层所对应的包路径,这里 -// *如果没有编写正确,会造成的在访问swagger2页面时没有接口信息出现 -// */ -// .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) -// .paths(PathSelectors.any()) -// .build().apiInfo(new ApiInfoBuilder() -// //标题 -// .title("基础框架系统开发文档API总览界面") -// //描述 -// .description("基础框架系统接口详细信息......") -// //版本号 -// .version("9.0") -// //联系方式 -//// .contact(new Contact("指尖上跳动的旋律","blog.csdn.net","xxx@qq.com")) -//// //许可证 -//// .license("指尖上跳动的旋律") -// //许可证访问链接 -//// .licenseUrl("https://blog.csdn.net/xuguoxing123") -// .build()); -// } - -// public void addResourceHandlers(ResourceHandlerRegistry registry) { -// registry.addResourceHandler("**/swagger-ui.html") -// .addResourceLocations("classpath:/META-INF/resources/"); -// registry.addResourceHandler("/webjars*") -// .addResourceLocations("classpath:/META-INF/resources/webjars/"); -// } - - - -// private ApiInfo apiInfo() { -// return new ApiInfoBuilder() -// // 设置页面标题 -// .title("使用swagger2构建后端api接口文档") -// // 描述 -// .description("欢迎访问后端接口文档,这里是描述信息") -// // 定义版本号 -// .version("1.0").build(); -// } - - -// @Bean -// public Docket createRestApi() { -// return new Docket(DocumentationType.SWAGGER_2) -// .apiInfo(apiInfo()) -// .select() -// .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) -// .paths(PathSelectors.any()) -// .build(); -// } -// @Bean -// RestDocConfig _swaggerConfig() -// { -// return RestDocConfig.builder() -// .apiTitle("rest doc ywpt") -// .apiDescription("用户信息系统") -// .apiVersion("1.0.0") -// .packages(Arrays.asList("com.hp.user.service.controller")) -// .build(); -// } - -// private ApiInfo apiInfo() { -// return new ApiInfoBuilder() -// .title("rest doc user") -// .description("用户信息系统") -//// .termsOfServiceUrl("http://www.cnblogs.com/congc/") -// .version(VERSION) -// .build(); -// } -// RestDocConfig _swaggerConfig() -// { -// return RestDocConfig.builder() -// .apiTitle("rest doc user") -// .apiDescription("用户信息系统") -// .apiVersion("1.0.0") -// .packages(Arrays.asList("com.hp.user.service.controller")) -// .build(); -// } -} From 42c9261a99b7b4e4d5dc88f577e4b1385b75c668 Mon Sep 17 00:00:00 2001 From: yeqd Date: Thu, 26 Nov 2020 18:38:58 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E6=B7=BB=E5=8A=A0id=E7=94=9F=E6=88=90?= =?UTF-8?q?=E5=99=A8=EF=BC=8Credis=EF=BC=8CmessageController?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../user/client/service/AccountService.java | 7 + .../user/client/service/MessageService.java | 22 +++ user-service/pom.xml | 6 + .../user/service/UserServiceApplaction.java | 5 +- .../controller/AuthenticationController.java | 35 ++-- .../service/controller/MessageController.java | 32 ++++ .../user/service/impl/AccountServiceImpl.java | 21 +++ .../user/service/impl/MessageServiceImpl.java | 28 +++ .../hp/user/service/redis/RedisOperation.java | 178 ++++++++++++++++++ .../main/java/com/hp/user/util/IdWorker.java | 156 +++++++++++++++ 10 files changed, 474 insertions(+), 16 deletions(-) create mode 100644 user-client/src/main/java/com/hp/user/client/service/MessageService.java create mode 100644 user-service/src/main/java/com/hp/user/service/controller/MessageController.java create mode 100644 user-service/src/main/java/com/hp/user/service/impl/MessageServiceImpl.java create mode 100644 user-service/src/main/java/com/hp/user/service/redis/RedisOperation.java create mode 100644 user-service/src/main/java/com/hp/user/util/IdWorker.java diff --git a/user-client/src/main/java/com/hp/user/client/service/AccountService.java b/user-client/src/main/java/com/hp/user/client/service/AccountService.java index 032b5a0..e90261a 100644 --- a/user-client/src/main/java/com/hp/user/client/service/AccountService.java +++ b/user-client/src/main/java/com/hp/user/client/service/AccountService.java @@ -9,5 +9,12 @@ package com.hp.user.client.service; * @since 2020-11-20 */ public interface AccountService { + + /** + * 登陆 + * @param phone 手机号 + * @param verificationCode 验证码 + */ + public void login(String phone,String verificationCode); } diff --git a/user-client/src/main/java/com/hp/user/client/service/MessageService.java b/user-client/src/main/java/com/hp/user/client/service/MessageService.java new file mode 100644 index 0000000..6be08e4 --- /dev/null +++ b/user-client/src/main/java/com/hp/user/client/service/MessageService.java @@ -0,0 +1,22 @@ +package com.hp.user.client.service; + +/** + * 信息服务 + * @author yeqid + * + */ +public interface MessageService { + + /** + * 发送验证码 + * @param phone 手机号 + */ + public void sendVerificationCode(String phone); + + /** + * 获取验证码 + * @param phone 手机号 + * @return 返回验证码 + */ + public String getVerificationCode(String phone); +} diff --git a/user-service/pom.xml b/user-service/pom.xml index ca69cbf..3e2787e 100644 --- a/user-service/pom.xml +++ b/user-service/pom.xml @@ -157,6 +157,12 @@ jackson-databind 2.9.5 + + + redis.clients + jedis + 2.9.0 + diff --git a/user-service/src/main/java/com/hp/user/service/UserServiceApplaction.java b/user-service/src/main/java/com/hp/user/service/UserServiceApplaction.java index 56e411c..0526928 100644 --- a/user-service/src/main/java/com/hp/user/service/UserServiceApplaction.java +++ b/user-service/src/main/java/com/hp/user/service/UserServiceApplaction.java @@ -7,6 +7,7 @@ import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.ComponentScan; import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource; +import com.hp.user.service.redis.RedisOperation; /** * 用户服务启动类 @@ -18,7 +19,7 @@ import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource; @SpringBootApplication @NacosPropertySource(dataId = "userdatasource", autoRefreshed = true) //不能加compentscan,加了 -@ComponentScan("com.hp.user.service.dao")//这个地方不能写错,写错的话会出现2个问题,如果写的路径扫描不到swaggerconfig那么页面会报错 +//@ComponentScan("com.hp.user.service.dao")//这个地方不能写错,写错的话会出现2个问题,如果写的路径扫描不到swaggerconfig那么页面会报错 //(Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. //The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually: ), //如果写的路径扫描不到controller那么页面不会有接口信息 @@ -26,5 +27,7 @@ import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource; public class UserServiceApplaction { public static void main(String[] args) { SpringApplication.run(UserServiceApplaction.class, args); + System.out.println(RedisOperation.getRedis().get("tst")); + RedisOperation.getRedis().close(); } } diff --git a/user-service/src/main/java/com/hp/user/service/controller/AuthenticationController.java b/user-service/src/main/java/com/hp/user/service/controller/AuthenticationController.java index 232dde4..a02b054 100644 --- a/user-service/src/main/java/com/hp/user/service/controller/AuthenticationController.java +++ b/user-service/src/main/java/com/hp/user/service/controller/AuthenticationController.java @@ -1,28 +1,39 @@ package com.hp.user.service.controller; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import com.hp.user.client.service.AccountService; + +import io.swagger.annotations.Api; + @RestController @RequestMapping("/authentication") +@Api(value="身份认证") public class AuthenticationController { + + @Autowired + private AccountService accountService; + + /** * 登录 - * @param account 账号 - * @param password 密码 + * @param phone 账号 + * @param verificationCode 验证码 */ @RequestMapping("/login") - public void login(String account,String password){ - + public void login(String phone,String verificationCode) { + accountService.login(phone, verificationCode); } /** * 登出 */ @RequestMapping("/loginOut") - public void loginOut(){ - + public void loginOut() { + } /** @@ -30,16 +41,10 @@ public class AuthenticationController { * 需要用户信息 */ @RequestMapping("/register") - public void register(){ + public void register() { } + + - /** - * 找回密码 - * @param account 账号 - */ - @RequestMapping("findPassword") - public void findPassword(String account){ - - } } diff --git a/user-service/src/main/java/com/hp/user/service/controller/MessageController.java b/user-service/src/main/java/com/hp/user/service/controller/MessageController.java new file mode 100644 index 0000000..11a07f1 --- /dev/null +++ b/user-service/src/main/java/com/hp/user/service/controller/MessageController.java @@ -0,0 +1,32 @@ +package com.hp.user.service.controller; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import com.hp.user.client.service.MessageService; + +import io.swagger.annotations.Api; + +/** + * 短信 + * @author yeqid + * + */ +@Api(value="短信") +@RestController +@RequestMapping("/area") +public class MessageController { + + @Autowired + private MessageService messageService; + + /** + * 发送验证码 + * @param phoneNumber + */ + @RequestMapping("/sendVerificationCode") + public void sendVerificationCode(String phoneNumber) { + messageService.sendVerificationCode(phoneNumber); + } +} diff --git a/user-service/src/main/java/com/hp/user/service/impl/AccountServiceImpl.java b/user-service/src/main/java/com/hp/user/service/impl/AccountServiceImpl.java index 40798aa..8e0174b 100644 --- a/user-service/src/main/java/com/hp/user/service/impl/AccountServiceImpl.java +++ b/user-service/src/main/java/com/hp/user/service/impl/AccountServiceImpl.java @@ -1,6 +1,10 @@ package com.hp.user.service.impl; import com.hp.user.client.service.AccountService; +import com.hp.user.client.service.MessageService; + +import org.apache.commons.codec.binary.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** @@ -13,5 +17,22 @@ import org.springframework.stereotype.Service; */ @Service public class AccountServiceImpl implements AccountService { + + @Autowired + private MessageService messageService; + + @Override + public void login(String phone, String verificationCode) { + try { + String code = messageService.getVerificationCode(phone); + if(StringUtils.equals(verificationCode, code)) { + //登陆成功 + }else { + //登陆失败,返回验证码 + } + }catch(Exception e) { + + } + } } diff --git a/user-service/src/main/java/com/hp/user/service/impl/MessageServiceImpl.java b/user-service/src/main/java/com/hp/user/service/impl/MessageServiceImpl.java new file mode 100644 index 0000000..3b6fc8f --- /dev/null +++ b/user-service/src/main/java/com/hp/user/service/impl/MessageServiceImpl.java @@ -0,0 +1,28 @@ +package com.hp.user.service.impl; + +import org.springframework.stereotype.Service; + +import com.hp.user.client.service.MessageService; + +/** + * 信息服务实现类 + * @author yeqid + * @since 2020/11/26 + * + */ +@Service +public class MessageServiceImpl implements MessageService { + + @Override + public void sendVerificationCode(String phone) { + // TODO Auto-generated method stub + + } + + @Override + public String getVerificationCode(String phone) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/user-service/src/main/java/com/hp/user/service/redis/RedisOperation.java b/user-service/src/main/java/com/hp/user/service/redis/RedisOperation.java new file mode 100644 index 0000000..e286f34 --- /dev/null +++ b/user-service/src/main/java/com/hp/user/service/redis/RedisOperation.java @@ -0,0 +1,178 @@ +package com.hp.user.service.redis; + +import java.io.IOException; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; + +@Component +public class RedisOperation implements ApplicationRunner{ + + @Value("${redis-cluster.redisUrlList}") + private String hostAndPort; + @Value("${redis-cluster.password}") + private String password; + //10.1.170.207:17000,10.1.170.207:17001,10.1.170.207:17002,10.1.170.207:17003,10.1.170.207:17004,10.1.170.207:17005 + private static JedisPool pool = null; + + public static Jedis getRedis() { + return pool.getResource(); + } + +// public RedisOperation() { +// jedis = pool.getResource(); +// jedis.close(); +// System.out.println(jedis); +// } + + +// @PostConstruct +// public void init() { +// +// } + + /** + * 从redis中获取数据 + * @param key + * @return + */ +// public String get(String key) { +// +// return jedis.get(key); +// } +// +// /** +// * 往redis中set数据 +// * @param key +// * @param value +// */ +// public void set(String key,String value) { +// jedis.set(key, value); +// } +// +// /** +// * 往redis中hset数据 +// * @param key +// * @param field +// * @param value +// */ +// public void hset(String key,String field,String value) { +// jedis.hset(key, field, value); +// } +// +// /** +// * 从redis中hgetAll数据 +// * @param key +// * @return +// */ +// public Map hgetAll(String key) { +// return jedis.hgetAll(key); +// } +// +// public String hget(String key,String filed) { +// return jedis.hget(key,filed); +// } +// +// public void hmset(String key,Map hash) { +// jedis.hmset(key, hash); +// } +// /** +// * 设置有效时间 +// * @param key +// * @param second +// */ +// public void expire(String key,int second) { +// jedis.expire(key, second); +// } +// +// /** +// * 往redis中存数据并且设置失效时间 +// * @param key +// * @param seconds +// * @param value +// */ +// public void setex(String key,int seconds,String value) { +// jedis.setex(key, seconds, value); +// } +// +// /** +// * 批量获取指定的多个key的数据 +// * @param keys +// * @return +// */ +// public List mget(String ...keys) { +// return jedis.mget(keys); +// } +// +// /** +// * 删除key +// * @param key +// */ +// public void del(String key) { +// jedis.del(key); +// } +// /** +// * 判断key +// * @param key +// * @return +// */ +// public boolean exists(String key) { +// return jedis.exists(key); +// } +// /** +// * 释放资源 +// */ +// public void close() { +// try { +// if(jedis != null) { +// jedis.close(); +// } +// +// } catch (Exception e) { +//// LOGGER.error("redis close fail={}",e.getMessage()); +// } +// } + + @Override + public void run(ApplicationArguments args) throws Exception { + System.out.print("redis"); +// JedisPool pool = null; + // common-pool配置 + if (pool == null) { + GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); + poolConfig.setMaxTotal(GenericObjectPoolConfig.DEFAULT_MAX_TOTAL * 10); + poolConfig.setMaxIdle(GenericObjectPoolConfig.DEFAULT_MAX_IDLE * 4); + poolConfig.setMinIdle(GenericObjectPoolConfig.DEFAULT_MAX_IDLE * 2); + +// JedisPool.borrowObject最大等待时间 + poolConfig.setMaxWaitMillis(1000L); + try { +// Set jedisClusterNodes = new HashSet(); +// String[] singleUrl = hostAndPort.trim().split(","); + String[] single = hostAndPort.split(":"); +// for (int i = 0; i < singleUrl.length; i++) { +// String[] single = singleUrl[i].split(":"); +// jedisClusterNodes.add(new HostAndPort(single[0],Integer.parseInt(single[1]))); +//// jedisClusterNodes.add(new HostAndPort(single[0], Integer.parseInt(single[1]), false)); +// } +// jedis = new JedisCluster(jedisClusterNodes,2000,20); +// jedis = new JedisCluster(jedisClusterNodes,1000,10,4,password,poolConfig); +// new JedisPool(poolConfig, singleUrl[0], singleUrl[1],1000, password); + pool= new JedisPool(poolConfig, single[0], Integer.parseInt(single[1]),1000, password); + } catch (Exception e) { + e.printStackTrace(); + } + } + + } +} \ No newline at end of file diff --git a/user-service/src/main/java/com/hp/user/util/IdWorker.java b/user-service/src/main/java/com/hp/user/util/IdWorker.java new file mode 100644 index 0000000..f80689c --- /dev/null +++ b/user-service/src/main/java/com/hp/user/util/IdWorker.java @@ -0,0 +1,156 @@ +package com.hp.user.util; + +/** + * Id生成器 + * @author yeqid + * + */ +public class IdWorker{ + + //下面两个每个5位,加起来就是10位的工作机器id + private long workerId; //工作id + private long datacenterId; //数据id + //12位的序列号 + private long sequence; + + public static IdWorker worker = null; + + public IdWorker(long workerId, long datacenterId, long sequence){ + // sanity check for workerId + if (workerId > maxWorkerId || workerId < 0) { + throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0",maxWorkerId)); + } + if (datacenterId > maxDatacenterId || datacenterId < 0) { + throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId)); + } + System.out.printf("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d", + timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId); + + this.workerId = workerId; + this.datacenterId = datacenterId; + this.sequence = sequence; + } + + //初始时间戳 + private long twepoch = 1525705533000l; + + //长度为5位 + private long workerIdBits = 5L; + private long datacenterIdBits = 5L; + //最大值 + private long maxWorkerId = -1L ^ (-1L << workerIdBits); + private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); + //序列号id长度 + private long sequenceBits = 12L; + //序列号最大值 + private long sequenceMask = -1L ^ (-1L << sequenceBits); + + //工作id需要左移的位数,12位 + private long workerIdShift = sequenceBits; + //数据id需要左移位数 12+5=17位 + private long datacenterIdShift = sequenceBits + workerIdBits; + //时间戳需要左移位数 12+5+5=22位 + private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; + + //上次时间戳,初始值为负数 + private long lastTimestamp = -1L; + + public long getWorkerId(){ + return workerId; + } + + public long getDatacenterId(){ + return datacenterId; + } + + public long getTimestamp(){ + return System.currentTimeMillis(); + } + + //下一个ID生成算法 + public synchronized long nextId() { + long timestamp = timeGen(); + + //获取当前时间戳如果小于上次时间戳,则表示时间戳获取出现异常 + if (timestamp < lastTimestamp) { + System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp); + throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", + lastTimestamp - timestamp)); + } + + //获取当前时间戳如果等于上次时间戳(同一毫秒内),则在序列号加一;否则序列号赋值为0,从0开始。 + if (lastTimestamp == timestamp) { + sequence = (sequence + 1) & sequenceMask; + if (sequence == 0) { + timestamp = tilNextMillis(lastTimestamp); + } + } else { + sequence = 0; + } + + //将上次时间戳值刷新 + lastTimestamp = timestamp; + + /** + * 返回结果: + * (timestamp - twepoch) << timestampLeftShift) 表示将时间戳减去初始时间戳,再左移相应位数 + * (datacenterId << datacenterIdShift) 表示将数据id左移相应位数 + * (workerId << workerIdShift) 表示将工作id左移相应位数 + * | 是按位或运算符,例如:x | y,只有当x,y都为0的时候结果才为0,其它情况结果都为1。 + * 因为个部分只有相应位上的值有意义,其它位上都是0,所以将各部分的值进行 | 运算就能得到最终拼接好的id + */ + return ((timestamp - twepoch) << timestampLeftShift) | + (datacenterId << datacenterIdShift) | + (workerId << workerIdShift) | + sequence; + } + + //获取时间戳,并与上次时间戳比较 + private long tilNextMillis(long lastTimestamp) { + long timestamp = timeGen(); + while (timestamp <= lastTimestamp) { + timestamp = timeGen(); + } + return timestamp; + } + + //获取系统时间戳 + private long timeGen(){ + return System.currentTimeMillis(); + } + + public static Long generactorId() { + if(worker == null) { + synchronized(IdWorker.class) { + if(worker == null) { + worker = new IdWorker(1,1,1); + } + } + } + return worker.nextId(); + } + + //---------------测试--------------- +// public static void main(String[] args) throws InterruptedException { +//// IdWorker worker = new IdWorker(1,1,1); +// Thread t1 = new Thread( new Runnable() {public void run() { for (int i = 0; i < 30; i++) { +// +// System.out.println(IdWorker.generactorId()); +// +// };} }, "t1"); +// Thread t2 = new Thread( new Runnable() {public void run() { for (int i = 0; i < 30; i++) { +// +// System.out.println(IdWorker.generactorId()); +// };} }, "t2"); +// Thread t3 = new Thread( new Runnable() {public void run() { for (int i = 0; i < 30; i++) { +// +// System.out.println(IdWorker.generactorId()); +// };} }, "t3"); +// t2.start(); +// t1.start(); +// t3.start(); +// t1.join(); +// t2.join(); +// } + +} \ No newline at end of file