@Override public TxGroup addTransactionGroup(String groupId,String uniqueKey, String taskId,int isGroup, String modelName) { ValueOperations<String, String> value = redisTemplate.opsForValue(); String key = key_prefix + groupId; String json = value.get(key); if (StringUtils.isEmpty(json)) { return null; } TxGroup txGroup = TxGroup.parser(json); if (txGroup != null) { TxInfo txInfo = new TxInfo(); txInfo.setModelName(modelName); txInfo.setKid(taskId); txInfo.setAddress(Constants.address); txInfo.setIsGroup(isGroup); txInfo.setUniqueKey(uniqueKey); txGroup.addTransactionInfo(txInfo); value.set(key, txGroup.toJsonString(), redis_save_max_time, TimeUnit.SECONDS); return txGroup; } return null; }
@Override @Transactional(propagation = Propagation.REQUIRED) public long unlike(Long feedId, Long uid) { if (feedId == null || uid == null) { return -1; } Like like = likeMapper.getLike(feedId, uid); if (like == null) { return -1; } else { int deleteResult = likeMapper.delete(like.getId()); if (deleteResult > 0) { ZSetOperations<String, String> feedLikes = this.template.opsForZSet(); ValueOperations<String, String> feedCount = this.template.opsForValue(); feedLikes.remove(KEY_FEED_LIKE + feedId, Long.toString(uid)); return feedCount.increment(KEY_FEED_LIKE_COUNT + feedId, -1); } return -1; } }
/** * 用户菜单列表 */ @RequestMapping("/user") public R user() { List<SysMenuEntity> menuList = null; Set<String> permissions = sysMenuService.getUserPermissions(getUserId()); ValueOperations<String, String> ops = this.template.opsForValue(); String keyMenu = getUserId() + "_menuList"; if (!template.hasKey(keyMenu)) { logger.debug("菜单从database读取"); menuList = sysMenuService.getUserMenuList(getUserId()); ops.set(keyMenu, JSON.toJSONString(menuList)); } else { logger.debug("菜单从redis读取"); menuList = JSONObject.parseArray(ops.get(keyMenu),SysMenuEntity.class); } return R.ok().put("menuList", menuList).put("permissions", permissions); }
@Test public void testRedisConfig() { ValueOperations<String, String> ops = stringRedisTemplate.opsForValue(); ops.set("test", "value"); Assert.assertEquals( "value" , ops.get("test")); Assert.assertNull( ops.get("test2") ); ValueOperations<String, Object> ops2 = redisTemplate.opsForValue(); UserDo userDo = new UserDo(); userDo.setId(1L); userDo.setUserId("userId"); userDo.setUserName("userName"); ops2.set("testUser", userDo); UserDo redisUser = (UserDo)ops2.get("testUser"); Assert.assertNotNull( redisUser ); Assert.assertTrue( 1L==redisUser.getId() ); Assert.assertEquals("userId", redisUser.getUserId()); Assert.assertEquals("userName", redisUser.getUserName()); }
/** * 缓存value操作 * * @param k key * @param v value * @param time time * @return boolean */ @Override public boolean cacheValue(String k, String v, long time) { String key = KEY_PREFIX_VALUE + k; try { ValueOperations<String, String> valueOps = redisTemplate.opsForValue(); valueOps.set(key, v); if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Throwable t) { LOGGER.error("缓存[" + key + "]失败, value[" + v + "]", t); } return false; }
@Test public void testOpsForList(){ List<User> roles = new ArrayList<>(); User user = new com.carlos.luke.model.User(1L, "luke", 20); roles.add(user); ValueOperations<String, Object> opsForList = redisTemplate.opsForValue(); opsForList.set("roles", roles); List<User> result = (List<User>) opsForList.get("roles"); System.out.println(result.get(0).getName()); }
@Test public void testOpsForMap(){ Map<String, String> score = new HashMap<>(); score.put("stuA", "89"); score.put("stuB", "63"); score.put("stuC", "94"); score.put("stuD", "21"); ValueOperations<String, Object> opsForList = redisTemplate.opsForValue(); opsForList.set("scores", score); Map<String, String> result = (Map<String, String>) opsForList.get("scores"); System.out.println(result.get("stuA")); }
/** * 获取String缓存并更新 * @param key * @return */ public T getStringAndUpDate(String key,int time){ ValueOperations<String, T> operations = redisTemplate.opsForValue(); T t = operations.get(key); if (t!=null) operations.set(key,t,time, TimeUnit.HOURS); return t; }
@Override public TxGroup createTransactionGroup() { String groupId = KidUtils.generateShortUuid(); TxGroup txGroup = new TxGroup(); txGroup.setStartTime(System.currentTimeMillis()); txGroup.setGroupId(groupId); String key = key_prefix + groupId; ValueOperations<String, String> value = redisTemplate.opsForValue(); value.set(key, txGroup.toJsonString(), redis_save_max_time, TimeUnit.SECONDS); return txGroup; }
@Override public int checkTransactionGroup(String groupId, String taskId) { ValueOperations<String, String> value = redisTemplate.opsForValue(); String key = key_prefix + groupId; String json = value.get(key); if (StringUtils.isEmpty(json)) { key = key_prefix_notify + groupId; json = value.get(key); if (StringUtils.isEmpty(json)) { return 0; } } TxGroup txGroup = TxGroup.parser(json); if(txGroup.getHasOver()==0){ long nowTime = System.currentTimeMillis(); long startTime = txGroup.getStartTime(); //超时清理数据 if(nowTime-startTime>(redis_save_max_time*1000)){ redisTemplate.delete(key); return 0; } return -1; } boolean res = txGroup.getState() == 1; if(!res) { return 0; } for (TxInfo info : txGroup.getList()) { if (info.getKid().equals(taskId)) { return info.getNotify()==0?1:0; } } return 0; }
@Override public boolean closeTransactionGroup(String groupId,int state) { ValueOperations<String, String> value = redisTemplate.opsForValue(); String key = key_prefix + groupId; String json = value.get(key); if (StringUtils.isEmpty(json)) { return false; } final TxGroup txGroup = TxGroup.parser(json); txGroup.setState(state); txGroup.setHasOver(1); transactionConfirmService.confirm(txGroup); return true; }
@Override public void dealTxGroup(TxGroup txGroup, boolean hasOk) { String key = key_prefix + txGroup.getGroupId(); if (!hasOk) { //未通知成功 if (txGroup.getState() == 1) { ValueOperations<String, String> value = redisTemplate.opsForValue(); String newKey = key_prefix_notify + txGroup.getGroupId(); value.set(newKey, txGroup.toJsonString()); } } redisTemplate.delete(key); }
/** * 读取缓存 * * @param key * @return */ public static Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; }
/** * 写入缓存 * * @param key * @param value * @return */ public static boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; }
/** * 写入缓存 * * @param key * @param value * @return */ public static boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; }
public User getUser(Integer id) { ValueOperations valueOperations = redisTemplate.opsForValue(); System.out.println(JSON.toJSON(valueOperations.get(USER_PREFIX + id))); User user = (User) valueOperations.get(USER_PREFIX + id); return user; }
@Override public long likeUserCount(Long feedId) { if (feedId == null) { return -1; } ValueOperations<String, String> feedCount = this.template.opsForValue(); String result = feedCount.get(KEY_FEED_LIKE_COUNT + feedId); if (StringUtils.isEmpty(result)) { return -1; } return Long.parseLong(result); }
public void set(String key, String value) { ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue(); boolean bExistent = this.stringRedisTemplate.hasKey(key); if (bExistent) { logger.info("this key is bExistent!"); } else { ops.set(key, value); } }
public void persistImageCaptcha(String sid,String capText){ StringRedisTemplate template= redisConfig.getTemplate(); String format = imageCaptchaFormat(sid); ValueOperations<String,String> obj = template.opsForValue(); obj.set(format,capText.toLowerCase()); template.expire(format , getImageTimeOut(), TimeUnit.MINUTES); }
public void persistPhoneCaptcha(String phone , String code){ StringRedisTemplate template = getTemplate(); String format = phoneCaptchaFormat(phone); ValueOperations<String,String> obj = getTemplate().opsForValue(); obj.set(format,code.toLowerCase()); template.expire(format ,getPhoneTimeOut(), TimeUnit.MINUTES); }
/** * 向redis缓存中放数据 * * @param key * @param value */ @Override public void putObject(Object key, Object value) { String strKey = ""; if (!(key instanceof String)) { strKey = Objects.toString(key); } ValueOperations operations = getRedisTemplate().opsForValue(); operations.set(strKey, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES); }
@Override public void putKey(String modelName, String uniqueKey, String key) { String val = modelName + "#" + uniqueKey; ValueOperations<String, String> operations = redisTemplate.opsForValue(); operations.set(key_prefix + key, val); operations.set(val_prefix + val, key); }
@Override public void removeKey(String modelName, String uniqueKey) { String val = modelName + "#" + uniqueKey; String mkey = val_prefix + val; ValueOperations<String, String> operations = redisTemplate.opsForValue(); String key = operations.get(mkey); String mval = operations.get(key_prefix + key); //if(val.equals(mval)) { redisTemplate.delete(key_prefix + key); //} redisTemplate.delete(mkey); }
/** * 轮训UUID * * @param pd * @return */ @RequestMapping(value = "/queryUUID") @ResponseBody public PageData queryUUID(@RequestBody PageData pd) { try { // 判断二维码状态 String UUID = pd.getString("uuid"); if (StringUtils.isNotBlank(UUID)) { PageData optionPageData = new PageData(); ValueOperations<String, Object> redisOpt = redisTemplate.opsForValue(); // 获取二维码扫描状态 String redisUUID = String.join("", redisKeyPre, UUID); if (redisTemplate.hasKey(redisUUID)) { PageData optionPd = (PageData) redisOpt.get(redisUUID); String uuidStatic = optionPd.getString("option"); optionPageData.put("option", uuidStatic); // 获取用户信息 String userToken=optionPd.getString("userToken"); if (StringUtils.isNotBlank(userToken)) { PageData userObj = (PageData)redisOpt.get(optionPd.getString("userToken")); optionPageData.put("token", userToken); optionPageData.put("userInfo", JSON.toJSONString(userObj.get("userInfo"))); } return WebResult.requestSuccess(optionPageData); } else { return WebResult.requestFailed(509, "二维码已过期!", null); } } else { return WebResult.requestFailed(500, "参数不正确", null); } } catch (Exception e) { e.printStackTrace(); return WebResult.requestFailed(400, "系统错误,请联系管理员", null); } }
/**md * 检验token * * @param pd * @return */ @RequestMapping(value = "/checkToken") @ResponseBody public PageData checkToken() { try { HttpServletRequest request = this.getRequest(); String userToken = request.getHeader("userKey");// 从header中获取 String phoneMac = request.getHeader("mac");// 从header中获取 if (StringUtils.isNotBlank(userToken) && StringUtils.isNotBlank(phoneMac)) { // 获取redis值,判断token是否存在和用户登录mac是否一致 if (redisTemplate.hasKey(userToken)) { ValueOperations<String, Object> redisOpt = redisTemplate.opsForValue(); PageData userPd = (PageData)redisOpt.get(userToken); String userMac = userPd.getString("loginMac"); if (userMac.equals(phoneMac)) { return WebResult.requestSuccess(userPd); } else { return WebResult.requestFailed(505, "用户token失效", null); } } else { return WebResult.requestFailed(505, "用户token失效", null); } } else { return WebResult.requestFailed(500, "参数不正确", null); } } catch (Exception e) { e.printStackTrace(); return WebResult.requestFailed(400, "系统错误,请联系管理员", null); } }
/** * 退出token * * @param pd * @return */ @RequestMapping(value = "/logoutToken") @ResponseBody public PageData logoutToken() { try { String userToken = this.getRequest().getHeader("userKey");// 从header中获取 String phoneMac = this.getRequest().getHeader("mac");// 从header中获取 if (StringUtils.isNotBlank(userToken) && StringUtils.isNotBlank(phoneMac)) { // 获取redis值,判断token是否存在和用户登录mac是否一致 if (redisTemplate.hasKey(userToken)) { ValueOperations<String, Object> redisOpt = redisTemplate.opsForValue(); PageData userPd = (PageData)redisOpt.get(userToken); String userMac = userPd.getString("loginMac"); if (userMac.equals(phoneMac)) { redisTemplate.delete(userToken); return WebResult.requestSuccess(); } else { return WebResult.requestFailed(502, "token已失效", null); } } else { return WebResult.requestFailed(502, "token已失效", null); } } else { return WebResult.requestFailed(500, "参数不正确", null); } } catch (Exception e) { e.printStackTrace(); return WebResult.requestFailed(400, "系统错误,请联系管理员", null); } }
/** * @Description: 获取微信token * @return * @return PageData * @throws */ @RequestMapping(value = "/weixinAccessToken") @ResponseBody public PageData weixinAccessToken() { try { ValueOperations<String, Object> redisOpt = redisTemplate.opsForValue(); if(redisTemplate.hasKey("WEIXINACCESSTOKEN")){ return WebResult.requestSuccess(redisOpt.get("WEIXINACCESSTOKEN")); }else{ LocalDateTime localTime=LocalDateTime.now(); HashMap pd=new HashMap(); pd.put("grant_type", "client_credential"); pd.put("appid", weixinAppid); pd.put("secret", weixinSecret); String info=HttpUtils.httpGet(weixinTockenUrl, pd, null); PageData tokenPd=JSON.parseObject(info, PageData.class); if(tokenPd.containsKey("access_token")){ int expiressIn=(int)tokenPd.get("expires_in"); localTime=localTime.plusSeconds(expiressIn); tokenPd.put("expires_in", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(localTime)); redisOpt.set("WEIXINACCESSTOKEN",tokenPd, expiressIn, TimeUnit.SECONDS); return WebResult.requestSuccess(tokenPd); }else{ return WebResult.requestFailed(505, "请求token失败,请联系管理员", null); } } } catch (Exception e) { e.printStackTrace(); return WebResult.requestFailed(400, "系统错误,请联系管理员", null); } }
/** * 初始化敏感词列表 * */ private void initfiltercode() { ValueOperations<String, Object> redisOpt = redisTemplate.opsForValue(); if(redisTemplate.hasKey(sensitiveKey)){ keysMap=(HashMap)redisOpt.get(sensitiveKey); }else{ addKeywords(getAllProperties());//构建二叉树 redisOpt.set(sensitiveKey, keysMap); } }
/** * 检查验证码 * * @param pd 如果type是“2”,则校验付款识别码;其它情况校验登录验证码。 * @return */ public PageData checkVerificationCode(PageData pd) { String recNum = pd.getString("recNum"); String msgCode = pd.getString("msgCode"); String type = pd.getString("type"); if (StringUtils.isNotBlank(recNum) && StringUtils.isNotBlank(msgCode)) { String msgToken = String.join("", MsgKeyPre, recNum); //如果是付款识别码,取识别码的value if (type.equals("2")) { msgToken = String.join("", payIdentifyCode, recNum); } // 获取redis值,判断token是否存在和用户传入一致 if (redisTemplate.hasKey(msgToken)) { ValueOperations<String, Object> redisOpt = redisTemplate.opsForValue(); String code = redisOpt.get(msgToken).toString(); if (code.equals(msgCode)) { return WebResult.requestSuccess(); } else { return WebResult.requestFailed(505, "短信验证码验证失败", null); } } else { return WebResult.requestFailed(505, "短信验证码验证失败", null); } } else { return WebResult.requestFailed(500, "参数不正确", null); } }
SimpleRedisLock(ValueOperations ops, String lockKey, String lockValue, int acquireTimeout, int expiredTimeout){ this.ops = ops; this.lockKey = lockKey; this.lockValue = lockValue; this.acquireTimeout = acquireTimeout; this.expiredTimeout = expiredTimeout; }
@Override public void run(String... args) throws Exception { ValueOperations<String, String> ops = this.template.opsForValue(); String key = "spring.boot.redis.test"; if (!this.template.hasKey(key)) { ops.set(key, "foo"); } System.out.println("Found key " + key + ", value=" + ops.get(key)); }
/** * 获取缓存 * * @param k key * @return string */ @Override public String getValue(String k) { try { ValueOperations<String, String> valueOps = redisTemplate.opsForValue(); return valueOps.get(KEY_PREFIX_VALUE + k); } catch (Throwable t) { LOGGER.error("获取缓存失败key[" + KEY_PREFIX_VALUE + k + ", Codeor[" + t + "]"); } return null; }
/** * 读取缓存 * * @param key * @return */ public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate .opsForValue(); result = operations.get(key); return result; }
/** * 写入缓存 * * @param key * @param value * @return */ public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate .opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { logger.error("系统异常",e); } return result; }
/** * 写入缓存 * * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate .opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { logger.error("系统异常",e); } return result; }
@Before public void setUp() throws Exception { redisTemplate = mock(RedisTemplate.class); valueOperations = mock(ValueOperations.class); redisConnection = mock(RedisConnection.class); redisOperations = mock(RedisOperations.class); redisConnectionFactory = mock(RedisConnectionFactory.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); when(redisTemplate.getConnectionFactory()).thenReturn(redisConnectionFactory); when(valueOperations.getOperations()).thenReturn(redisOperations); when(redisTemplate.getConnectionFactory().getConnection()).thenReturn(redisConnection); idempotentRepository = new RedisStringIdempotentRepository(redisTemplate, REPOSITORY); idempotentRepository.setExpiry(1000L); }
@Test @SuppressWarnings("unchecked") public void saveNode() { ValueOperations opsForValue = mock(ValueOperations.class); doReturn(opsForValue).when(redisTemplate).opsForValue(); redisService.saveNode(nodeAsJson); verify(redisTemplate).opsForValue(); verify(opsForValue).set(eq("virtual:key1"), any(Node.class)); }