@Before public void setUp() { MockitoAnnotations.initMocks(this); Map<String, BoundValueOperations> map = Maps.newHashMap(); Map<String, Long> longMap = Maps.newHashMap(); when(redisTemplate.boundValueOps(any())).thenAnswer(invocation -> { String key = invocation.getArgument(0); BoundValueOperations mock = map.computeIfAbsent(key, k -> Mockito.mock(BoundValueOperations.class)); when(mock.increment(anyLong())).thenAnswer(invocationOnMock -> { long value = invocationOnMock.getArgument(0); return longMap.compute(key, (k, v) -> ((v != null) ? v : 0L) + value); }); return mock; }); target = new RedisRateLimiter(rateLimiterErrorHandler, redisTemplate); }
private void saveSecurityContext(HttpServletRequest request, HttpServletResponse response, SecurityContext context){ String sid = getSessionId(request); if(StringUtils.isBlank(sid)){ SaveToSessionResponseWrapper responseWrapper = WebUtils.getNativeResponse(response, SaveToSessionResponseWrapper.class); sid = responseWrapper.getSid(); saveSessionCookies(request, response, sid); } LoginUserDetails loginUser = SecurityUtils.getCurrentLoginUser(context); if(loginUser!=null){ loginUser.setToken(sid); } BoundValueOperations<String, SecurityContext> bondOps = getSessionBoundOps(sid); //当前spring-data-redis版本不支持setex,分成两个操作 bondOps.set(context); setSecurityContextExpireTime(request); }
/** * BoundKeyOperations、BoundValueOperations、BoundSetOperations * BoundListOperations、BoundSetOperations、BoundHashOperations */ @Test public void testBoundOperations() { BoundValueOperations<String, Object> boundValueOperations = redisTemplate.boundValueOps("BoundTest"); //设置值 // boundValueOperations.set("test12345"); //设置过期时间 // boundValueOperations.expire(100, TimeUnit.SECONDS); //重命名Key // boundValueOperations.rename("BoundTest123"); System.out.println("key: " + boundValueOperations.getKey()); System.out.println(boundValueOperations.get()); System.out.println("expire: " + boundValueOperations.getExpire()); }
public void counterIncrease(String key, Integer i, Long expSec) { Preconditions.checkArgument(StringUtils.isNotEmpty(key), "key is empty"); Preconditions.checkNotNull(i, "counterIncrease num is null"); BoundValueOperations<String, Object> b = redisTemplate.boundValueOps(key); b.increment(i); if(expSec != null && b.getExpire() != null) { redisTemplate.expire(key, expSec, TimeUnit.SECONDS); } }
public Long counterGet(String key) { Preconditions.checkArgument(StringUtils.isNotEmpty(key), "key is empty"); BoundValueOperations<String, Object> b = redisTemplate.boundValueOps(key); Object val = b.get(0, -1); return val == null ? null : Long.valueOf((String)val); }
/** * 保存到redis * * @param key 唯一标示 * @param ttl 失效时长(单位:秒) * @param type 事件类型 */ public void store(Serializable key, int ttl, RedisEventType type) { Assert.notNull(key, "key不能为空!"); Assert.notNull(type, "type不能为空!"); if (ttl <= 0) { // 抛出事件 publishEvent(new RedisEvent(this, key, type)); return; } BoundValueOperations<String, Object> operations = redisTemplate.boundValueOps(REDIS_KEY_PREFIX + type.getType() + REDIS_KEY_SEPARATOR + key); operations.set(key, ttl * 1000, TimeUnit.MILLISECONDS); }
@Test @Override @SuppressWarnings("unchecked") public void testRateLimitExceedCapacity() throws Exception { BoundValueOperations ops = mock(BoundValueOperations.class); when(this.redisTemplate.boundValueOps(anyString())).thenReturn(ops); when(ops.increment(anyLong())).thenReturn(3L); super.testRateLimitExceedCapacity(); }
@Test @Override @SuppressWarnings("unchecked") public void testRateLimit() throws Exception { BoundValueOperations ops = mock(BoundValueOperations.class); when(this.redisTemplate.boundValueOps(anyString())).thenReturn(ops); when(ops.increment(anyLong())).thenReturn(2L); this.request.setRequestURI("/serviceA"); this.request.setRemoteAddr("10.0.0.100"); assertTrue(this.filter.shouldFilter()); for (int i = 0; i < 2; i++) { this.filter.run(); } String key = "null_serviceA_serviceA_10.0.0.100_anonymous"; String remaining = this.response.getHeader(RateLimitPreFilter.REMAINING_HEADER + key); assertEquals("0", remaining); TimeUnit.SECONDS.sleep(2); when(ops.increment(anyLong())).thenReturn(1L); this.filter.run(); remaining = this.response.getHeader(RateLimitPreFilter.REMAINING_HEADER + key); assertEquals("1", remaining); }
private long get(BoundValueOperations valueOperations) { Object value = valueOperations.get(); if (value == null) { return 0; } if (value instanceof Number) { return ((Number) value).longValue(); } if (value instanceof String) { return StringUtils.isEmpty(value) ? 0 : Long.parseLong(value.toString()); } return 0; }
protected void addOps(final EmailSchedulingData emailSchedulingData) { final String orderingKey = orderingKey(emailSchedulingData); final String valueKey = emailSchedulingData.getId(); final double score = calculateScore(emailSchedulingData); BoundZSetOperations<String, String> orderingZSetOps = orderingTemplate.boundZSetOps(orderingKey); orderingZSetOps.add(valueKey, score); orderingZSetOps.persist(); BoundValueOperations<String, EmailSchedulingData> valueValueOps = valueTemplate.boundValueOps(valueKey); valueValueOps.set(emailSchedulingData); valueValueOps.persist(); }
private void setSecurityContextExpireTime(HttpServletRequest request){ String sid = getSessionId(request); if(StringUtils.isBlank(sid)) return ; BoundValueOperations<String, SecurityContext> bondOps = getSessionBoundOps(sid); int invalidTime = request.getSession().getMaxInactiveInterval(); bondOps.expire(invalidTime, TimeUnit.SECONDS); }
@Override public BoundValueOperations<K, V> boundValueOps(K key) { try { return redisTemplate.boundValueOps(key); } catch (Exception ex) { throw new RedisBaoException(ex); } }
/** * @param args */ public static void main(String[] args) { JedisShardInfo jedisShardInfo1 = new JedisShardInfo(ip1); jedisShardInfo1.setPassword(JedisConstant.password); JedisShardInfo jedisShardInfo2 = new JedisShardInfo(ip2); jedisShardInfo2.setPassword(JedisConstant.password); List<JedisShardInfo> jedisShardInfos = new ArrayList<JedisShardInfo>(); jedisShardInfos.add(jedisShardInfo1); jedisShardInfos.add(jedisShardInfo2); JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxActive(JedisConstant.maxActive); poolConfig.setMaxIdle(JedisConstant.maxIdle); poolConfig.setMaxWait(JedisConstant.maxWait); poolConfig.setTestOnBorrow(JedisConstant.testOnBorrow); poolConfig.setTestOnReturn(JedisConstant.testOnReturn); ShardedJedisPool shardedJedisPool = new ShardedJedisPool(poolConfig, jedisShardInfos); JedisConnectionFactory factory = new JedisConnectionFactory(jedisShardInfo1); StringRedisTemplate template = new StringRedisTemplate(factory); for (int i = 0; i < 2000; i++) { String key = "howsun_" + i; BoundValueOperations<String, String> v = template.boundValueOps(key); //jedis.set(key, UUID.randomUUID().toString()); System.out.println(key + "\t" + v.get() + "\t" + factory.getHostName()); } }
@Override public BoundValueOperations<K, V> boundValueOps(K key) { throw new MethodNotSupportException("myRedisTemplate not support this method : boundValueOps(K key) , please use opsForXX"); //return new DefaultBoundValueOperations<K, V>(key, this); }
protected EmailSchedulingData getOps(final String id) { //valueTemplate. BoundValueOperations<String, EmailSchedulingData> boundValueOps = valueTemplate.boundValueOps(id); EmailSchedulingData emailSchedulingData = boundValueOps.get(); return emailSchedulingData; }
private BoundValueOperations<String, SecurityContext> getSessionBoundOps(String sid){ // String sid = getSessionId(httpSession); String skey = getSecuritySessionKey(sid); // return this.redisTemplate.boundHashOps(skey); return this.redisTemplate.boundValueOps(skey); }
BoundValueOperations<K, V> boundValueOps(K key);