Here are the examples of the java api org.springframework.data.redis.core.StringRedisTemplate taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
595 Examples
19
Source : RedisAutoConfigure.java
with Apache License 2.0
from zuihou
with Apache License 2.0
from zuihou
@Bean("stringRedisTemplate")
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate();
setSerializer(factory, template);
return template;
}
19
Source : RedisSender.java
with GNU General Public License v2.0
from ZoeShaw101
with GNU General Public License v2.0
from ZoeShaw101
/**
* 生产者
* @author 科帮网 By https://blog.52itstyle.com
*/
@Service
public clreplaced RedisSender {
@Autowired
private StringRedisTemplate stringRedisTemplate;
// 向通道发送消息的方法
public void sendChannelMess(String channel, String message) {
stringRedisTemplate.convertAndSend(channel, message);
}
}
19
Source : SpringRedisPhoneCodeCache.java
with MIT License
from zidoshare
with MIT License
from zidoshare
public void setTemplate(StringRedisTemplate template) {
this.template = template;
}
19
Source : StringRedisTemplateSecurity.java
with MIT License
from zidoshare
with MIT License
from zidoshare
/**
* 可以直接注入使用
* <p>
* 注意不同的业务(例如对接网易与对接其他第三方接口),
* 在注入bean的时候,记得使用命名bean或者可以直接继承实现,注入下一层的bean
*
* @author zido
*/
public clreplaced StringRedisTemplateSecurity extends AbstractSecurity {
private String nonceKey;
private StringRedisTemplate template;
public StringRedisTemplateSecurity(String token, String nonceKey, StringRedisTemplate template) {
super(token);
this.nonceKey = nonceKey;
this.template = template;
}
@Override
protected void clearNonce() {
template.delete(nonceKey);
}
@Override
protected boolean addNonce(String nonce) {
return 1 == template.opsForSet().add(nonceKey, nonce);
}
}
19
Source : RedisPhoneCodeConfiguration.java
with MIT License
from zidoshare
with MIT License
from zidoshare
@Bean
@ConditionalOnMissingBean(PhoneCodeCache.clreplaced)
public PhoneCodeCache phoneCodeCache(@Autowired CoffeeSecurityProperties properties, @Autowired @Qualifier(TEMPLATE_BEAN_NAME) StringRedisTemplate template) {
SpringRedisPhoneCodeCache cache = new SpringRedisPhoneCodeCache();
cache.setKeyPrefix(properties.getPhoneCode().getKeyPrefix());
if (properties.getPhoneCode().getTimeout() != null) {
cache.setTimeout(properties.getPhoneCode().getTimeout(), TimeUnit.SECONDS);
}
cache.setTemplate(template);
return cache;
}
19
Source : RedisCacheConfig.java
with Apache License 2.0
from zhupanlinch
with Apache License 2.0
from zhupanlinch
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate redisTemplate = new StringRedisTemplate(factory);
// JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
// 这里如果启用fastjson序列化对象到redis的话 启动必须加参数 -Dfastjson.parser.autoTypeSupport=true
// RedisSerializer fastJson = fastJson2JsonRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.clreplaced);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
19
Source : RedisLockUtil.java
with GNU General Public License v3.0
from zhshuixian
with GNU General Public License v3.0
from zhshuixian
/**
* 进行加锁与解锁
*
* @author xiaoxian
*/
@Component
public clreplaced RedisLockUtil {
Logger logger = LoggerFactory.getLogger(this.getClreplaced());
@Resource
private StringRedisTemplate stringRedisTemplate;
public boolean lock(String key, String value, long timeout, TimeUnit timeUnit) {
/* // long timeout = 100000;
// TimeUnit timeUnit = TimeUnit.SECONDS;
logger.info("开始获得锁 key =" + value);
Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, value, 15, TimeUnit.SECONDS);
return result != null && result;*/
Boolean lockStat = stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(key.getBytes(StandardCharsets.UTF_8), value.getBytes(StandardCharsets.UTF_8), Expiration.from(timeout, timeUnit), RedisStringCommands.SetOption.SET_IF_ABSENT));
return lockStat != null && lockStat;
}
public boolean unlock(String key, String value) {
/* 不要使用这种方式
try {
String redisValue = stringRedisTemplate.opsForValue().get(key);
if (redisValue != null && redisValue.equals(value)) {
// 释放锁
stringRedisTemplate.opsForValue().getOperations().delete(key);
}
return true;
} catch (Exception e) {
logger.error("解锁失败");
}
*/
try {
// 使用 lua 脚本
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Boolean unLockStat = stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.eval(script.getBytes(), ReturnType.BOOLEAN, 1, key.getBytes(StandardCharsets.UTF_8), value.getBytes(StandardCharsets.UTF_8)));
return unLockStat == null || !unLockStat;
} catch (Exception e) {
logger.error("解锁失败 key = {}", key);
return false;
}
}
}
19
Source : RedisController.java
with GNU General Public License v3.0
from zhshuixian
with GNU General Public License v3.0
from zhshuixian
/**
* @author xiaoxian
*/
@RestController
@CacheConfig(cacheNames = "users")
public clreplaced RedisController {
@Resource
private StringRedisTemplate stringTemplate;
@Resource
private RedisTemplate<String, User> redisTemplate;
@Resource
private UserRepository userRepository;
@Resource
private UserMapper userMapper;
@RequestMapping("/setString")
public String setString(@RequestParam(value = "key") String key, @RequestParam(value = "value") String value) {
stringTemplate.opsForValue().set(key, value);
return "ok";
}
@RequestMapping("/getString")
public String getString(@RequestParam(value = "key") String key) {
return stringTemplate.opsForValue().get(key);
}
// TODO User 类存入和时间限制
@RequestMapping(value = "/setUser")
public String setUser(@RequestBody User user) {
redisTemplate.opsForValue().set(user.getUsername(), user, Duration.ofMinutes(1));
return "ok";
}
@RequestMapping("/getUser")
public User getUser(@RequestParam(value = "key") String key) {
return redisTemplate.opsForValue().get(key);
}
@RequestMapping("/delUser")
public User delUser(@RequestParam(value = "key") String key) {
User user = redisTemplate.opsForValue().get(key);
redisTemplate.delete(key);
return user;
}
// TODO 数据库缓存
@RequestMapping("/select")
@Cacheable(key = "#username")
public User select(@RequestParam(value = "username") String username) {
return userRepository.findByUsername(username);
}
@RequestMapping("/update")
@CachePut(key = "#user.username")
public User update(@RequestBody User user) {
return userRepository.save(user);
}
@RequestMapping("/delete")
@CacheEvict(key = "#username")
public User delete(@RequestParam(value = "username") String username) {
User user = select(username);
userRepository.delete(user);
return user;
}
@RequestMapping("/deleteAllCache")
@CacheEvict(allEntries = true)
public String deleteAllCache() {
// 删除所有缓存
return "OK";
}
@RequestMapping("/mySelect")
@Cacheable(value = "users", key = "#username")
public User mySelect(@RequestParam(value = "username") String username) {
return userMapper.selectByUsername(username);
}
@RequestMapping("/myUpdate")
@CachePut(value = "users", key = "#user.username")
public User myUpdate(@RequestBody User user) {
userMapper.update(user);
return userMapper.selectByUsername(user.getUsername());
}
@RequestMapping("/myDelete")
@CacheEvict(value = "users", key = "#username")
public User myDelete(@RequestParam(value = "username") String username) {
userMapper.delete(username);
return userMapper.selectByUsername(username);
}
}
19
Source : RedisConfig.java
with GNU General Public License v3.0
from zhshuixian
with GNU General Public License v3.0
from zhshuixian
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.clreplaced)
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
19
Source : RouteService.java
with Apache License 2.0
from zhoutaoo
with Apache License 2.0
from zhoutaoo
@Service
@Slf4j
public clreplaced RouteService implements IRouteService {
private static final String GATEWAY_ROUTES = "gateway_routes::";
@Autowired
private StringRedisTemplate stringRedisTemplate;
@CreateCache(name = GATEWAY_ROUTES, cacheType = CacheType.REMOTE)
private Cache<String, RouteDefinition> gatewayRouteCache;
private Map<String, RouteDefinition> routeDefinitionMaps = new HashMap<>();
@PostConstruct
private void loadRouteDefinition() {
log.info("loadRouteDefinition, 开始初使化路由");
Set<String> gatewayKeys = stringRedisTemplate.keys(GATEWAY_ROUTES + "*");
if (CollectionUtils.isEmpty(gatewayKeys)) {
return;
}
log.info("预计初使化路由, gatewayKeys:{}", gatewayKeys);
// 去掉key的前缀
Set<String> gatewayKeyIds = gatewayKeys.stream().map(key -> {
return key.replace(GATEWAY_ROUTES, StringUtils.EMPTY);
}).collect(Collectors.toSet());
Map<String, RouteDefinition> allRoutes = gatewayRouteCache.getAll(gatewayKeyIds);
log.info("gatewayKeys:{}", allRoutes);
// 以下代码原因是,jetcache将RouteDefinition返序列化后,uri发生变化,未初使化,导致路由异常,以下代码是重新初使化uri
allRoutes.values().forEach(routeDefinition -> {
try {
routeDefinition.setUri(new URI(routeDefinition.getUri().toASCIIString()));
} catch (URISyntaxException e) {
log.error("网关加载RouteDefinition异常:", e);
}
});
routeDefinitionMaps.putAll(allRoutes);
log.info("共初使化路由信息:{}", routeDefinitionMaps.size());
}
@Override
public Collection<RouteDefinition> getRouteDefinitions() {
return routeDefinitionMaps.values();
}
@Override
public boolean save(RouteDefinition routeDefinition) {
routeDefinitionMaps.put(routeDefinition.getId(), routeDefinition);
log.info("新增路由1条:{},目前路由共{}条", routeDefinition, routeDefinitionMaps.size());
return true;
}
@Override
public boolean delete(String routeId) {
routeDefinitionMaps.remove(routeId);
log.info("删除路由1条:{},目前路由共{}条", routeId, routeDefinitionMaps.size());
return true;
}
}
19
Source : RedisSender.java
with Apache License 2.0
from zhoutaoo
with Apache License 2.0
from zhoutaoo
@Component
public clreplaced RedisSender {
private final Logger logger = LoggerFactory.getLogger(this.getClreplaced());
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Bean
RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic("chat"));
logger.info("init container:{}", listenerAdapter);
return container;
}
public void send(String channel, String message) {
logger.info("{}=>{}", channel, message);
stringRedisTemplate.convertAndSend(channel, message);
}
}
19
Source : RedisUtil.java
with GNU Affero General Public License v3.0
from zhouhuan751312
with GNU Affero General Public License v3.0
from zhouhuan751312
/**
* Redis工具类
* @author zhouzhou
* @date 2020-03-12 15:35
*/
@Component
public clreplaced RedisUtil {
/**
* 是否开启Redis
*/
/**
* 是否开启redis缓存 true开启 false关闭
*/
@Value("${fast.redis.enabled: true}")
private Boolean enabled;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Resource(name = "redisTemplate")
private ValueOperations<String, String> valueOperations;
@Resource(name = "redisTemplate")
private HashOperations<String, String, Object> hashOperations;
@Resource(name = "redisTemplate")
private ListOperations<String, Object> listOperations;
@Resource(name = "redisTemplate")
private SetOperations<String, Object> setOperations;
@Resource(name = "redisTemplate")
private ZSetOperations<String, Object> zSetOperations;
/**
* 默认过期时长,单位:秒
*/
public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
/**
* 默认监控过期时长,单位:秒
*/
public final static long DEFAULT_EXPIRE_MT = 60 * 2;
public final static long MINUTE = 60;
/**
* 不设置过期时长
*/
public final static long NOT_EXPIRE = -1;
/**
* 数据存放Set集合
*/
public void add(String key, long expire, String... values) {
if (enabled) {
setOperations.add(key, values);
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
}
}
public void delSet(String key, String... values) {
if (enabled) {
setOperations.remove(key, values);
}
}
/**
* 通过Key获取之前存放的Set集合
*/
public Set<Object> getSets(String key) {
if (enabled) {
return setOperations.members(key);
}
return null;
}
public void set(String key, Object value, long expire) {
if (enabled) {
valueOperations.set(key, toJson(value));
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
}
}
public void setMillse(String key, Object value, long expire) {
if (enabled) {
valueOperations.set(key, toJson(value));
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.MILLISECONDS);
}
}
}
public void set(String key, Object value) {
if (enabled) {
set(key, value, DEFAULT_EXPIRE);
}
}
public void setSeConds(String key, Object value, long expire) {
if (enabled) {
valueOperations.set(key, toJson(value));
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
}
}
public void set(String key, Object value, int out) {
if (enabled) {
set(key, value, NOT_EXPIRE);
}
}
public void setApi(String key, Object value) {
if (enabled) {
set(key, value, DEFAULT_EXPIRE_MT);
}
return;
}
public <T> T get(String key, Clreplaced<T> clazz, long expire) {
if (enabled) {
String value = valueOperations.get(key);
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value == null ? null : fromJson(value, clazz);
}
return null;
}
public <T> T get(String key, Clreplaced<T> clazz) {
if (enabled) {
return get(key, clazz, NOT_EXPIRE);
}
return null;
}
public String get(String key, long expire) {
if (enabled) {
String value = valueOperations.get(key);
if (expire != NOT_EXPIRE) {
redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
return value;
}
return null;
}
public String get(String key) {
if (enabled) {
return get(key, NOT_EXPIRE);
}
return null;
}
public void delete(String key) {
if (enabled) {
redisTemplate.delete(key);
}
}
public boolean deletes(String key) {
if (enabled) {
Set<String> keys = redisTemplate.keys(key);
return redisTemplate.delete(keys) > 0;
}
return false;
}
public boolean isEnabled() {
return enabled;
}
/**
* Object转成JSON数据
*/
private String toJson(Object object) {
if (object instanceof Integer || object instanceof Long || object instanceof Float || object instanceof Double || object instanceof Boolean || object instanceof String) {
return String.valueOf(object);
}
return JSON.toJSONString(object);
}
/**
* JSON数据,转成Object
*/
private <T> T fromJson(String json, Clreplaced<T> clazz) {
return JSON.parseObject(json, clazz);
}
}
19
Source : SpringBootRedisTemplateTest.java
with GNU General Public License v3.0
from zhonghuasheng
with GNU General Public License v3.0
from zhonghuasheng
@RunWith(SpringRunner.clreplaced)
@SpringBootTest(clreplacedes = Application.clreplaced)
public clreplaced SpringBootRedisTemplateTest {
@Autowired
private ApplicationContext context;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void stringRedisTemplateTest() {
System.out.println(stringRedisTemplate);
stringRedisTemplate.opsForValue().set("db-type", "mongodb");
System.out.println(stringRedisTemplate.opsForValue().get("db-type"));
stringRedisTemplate.opsForValue().setIfAbsent("forward", "1", 24, TimeUnit.HOURS);
for (int i = 0; i < 10; i++) {
stringRedisTemplate.opsForValue().increment("forward", 1);
System.out.println(stringRedisTemplate.opsForValue().get("forward"));
}
}
}
19
Source : ForwardServiceImpl.java
with GNU General Public License v3.0
from zhonghuasheng
with GNU General Public License v3.0
from zhonghuasheng
@Service
public clreplaced ForwardServiceImpl implements ForwardService {
private static final String PREFIX = "music:forward";
@Autowired
StringRedisTemplate stringRedisTemplate;
@Override
public void forward(Long id) {
if (stringRedisTemplate.hasKey(PREFIX)) {
stringRedisTemplate.opsForValue().increment(PREFIX, 1);
System.out.println("After incr, the value is: " + stringRedisTemplate.opsForValue().get(PREFIX));
} else {
setKey(PREFIX, "101");
}
}
public synchronized void setKey(String key, String value) {
if (!stringRedisTemplate.hasKey(PREFIX)) {
stringRedisTemplate.opsForValue().setIfAbsent(key, value, 24, TimeUnit.HOURS);
} else {
stringRedisTemplate.opsForValue().increment(PREFIX, 1);
}
System.out.println("After execute setKey method, the value is: " + stringRedisTemplate.opsForValue().get(key));
}
}
19
Source : RedisController.java
with GNU General Public License v3.0
from zhonghuasheng
with GNU General Public License v3.0
from zhonghuasheng
@RestController
@RequestMapping("/redis")
public clreplaced RedisController {
@Autowired
StringRedisTemplate stringRedisTemplate;
@GetMapping("/get/{key}")
public String get(@PathVariable("key") String key) {
String val = stringRedisTemplate.opsForValue().get(key);
return val;
}
}
19
Source : RedisAutoConfig.java
with Apache License 2.0
from zhengkaixing
with Apache License 2.0
from zhengkaixing
@Bean
public StringRedisTemplate userRedisTemplate(LettuceConnectionFactory userLettuceConnectionFactory) {
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(userLettuceConnectionFactory);
return redisTemplate;
}
19
Source : RedisAutoConfig.java
with Apache License 2.0
from zhengkaixing
with Apache License 2.0
from zhengkaixing
@Bean
public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory defaultLettuceConnectionFactory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(defaultLettuceConnectionFactory);
return stringRedisTemplate;
}
19
Source : RedisAutoConfig.java
with Apache License 2.0
from zhengkaixing
with Apache License 2.0
from zhengkaixing
@Bean
public StringRedisTemplate lockRedisTemplate(LettuceConnectionFactory lockLettuceConnectionFactory) {
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(lockLettuceConnectionFactory);
return redisTemplate;
}
19
Source : LockComponent.java
with Apache License 2.0
from zhengkaixing
with Apache License 2.0
from zhengkaixing
/**
* Description:
* User: admin
* Date: 2019-02-07
* Time: 上午11:40
*/
@Component
public clreplaced LockComponent {
@Autowired
private StringRedisTemplate lockRedisTemplate;
private static final String LOCK_PREFIX = "LOCK_PREFIX_";
/**
* 获取乐观锁
*
* @param key
* @param timeoutSec 锁过期时间
* @return
*/
public boolean tryLock(String key, Integer timeoutSec) {
return lockRedisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + key, System.currentTimeMillis() + "", Duration.ofSeconds(timeoutSec));
}
public boolean tryLockMulti(Collection<String> keys, Integer timeoutSec) {
Map<String, String> map = new HashMap<>();
String now = System.currentTimeMillis() + "";
for (String key : keys) {
map.put(key, now);
}
boolean suc = lockRedisTemplate.opsForValue().multiSetIfAbsent(map);
if (suc) {
keys.forEach(item -> {
lockRedisTemplate.expire(item, timeoutSec, TimeUnit.SECONDS);
});
}
return suc;
}
public void release(String key) {
lockRedisTemplate.delete(LOCK_PREFIX + key);
}
public boolean hashPut(String table, String key) {
return lockRedisTemplate.opsForHash().putIfAbsent(table, key, key);
}
public boolean hashContains(String table, String key) {
return lockRedisTemplate.opsForHash().hasKey(table, key);
}
public void hashDel(String table, String key) {
lockRedisTemplate.opsForHash().delete(table, key);
}
}
19
Source : CacheComponent.java
with Apache License 2.0
from zhengkaixing
with Apache License 2.0
from zhengkaixing
/**
* Created by admin on 2019/3/22.
*/
@Component
public clreplaced CacheComponent {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void putObj(String key, Object obj, Integer expireSec) {
if (expireSec != null) {
stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(obj), expireSec, TimeUnit.SECONDS);
} else {
stringRedisTemplate.opsForValue().set(key, JSONObject.toJSONString(obj));
}
}
public Long incRaw(String key) {
return stringRedisTemplate.opsForValue().increment(key);
}
public <T> T getObj(String key, Clreplaced<T> clazz) {
String json = stringRedisTemplate.opsForValue().get(key);
if (StringUtils.isEmpty(json)) {
return null;
}
return JSONObject.parseObject(json, clazz);
}
public <T> List<T> getObjList(String key, Clreplaced<T> clazz) {
String json = stringRedisTemplate.opsForValue().get(key);
if (StringUtils.isEmpty(json)) {
return null;
}
return JSONObject.parseArray(json, clazz);
}
public void putHashAll(String key, Map<String, String> map, Integer expireSec) {
stringRedisTemplate.opsForHash().putAll(key, map);
stringRedisTemplate.expire(key, expireSec, TimeUnit.SECONDS);
}
public Map<String, String> getHashAll(String key) {
if (!stringRedisTemplate.hasKey(key)) {
return null;
}
return (Map) stringRedisTemplate.opsForHash().entries(key);
}
public <T> T getHashObj(String hashName, String key, Clreplaced<T> clazz) {
String o = (String) stringRedisTemplate.opsForHash().get(hashName, key);
if (StringUtils.isEmpty(o)) {
return null;
}
return JSONObject.parseObject(o, clazz);
}
public String getHashRaw(String hashName, String key) {
String o = (String) stringRedisTemplate.opsForHash().get(hashName, key);
if (StringUtils.isEmpty(o)) {
return null;
}
return o;
}
public <T> List<T> getHashArray(String hashName, String key, Clreplaced<T> clazz) {
String o = (String) stringRedisTemplate.opsForHash().get(hashName, key);
if (StringUtils.isEmpty(o)) {
return null;
}
return JSONObject.parseArray(o, clazz);
}
public Long incHashRaw(String hashName, String key, long delta) {
return stringRedisTemplate.opsForHash().increment(hashName, key, delta);
}
public void putHashRaw(String hashName, String key, String str, Integer expireSec) {
boolean hasKey = stringRedisTemplate.hasKey(key);
stringRedisTemplate.opsForHash().put(hashName, key, str);
if (!hasKey) {
stringRedisTemplate.expire(key, expireSec, TimeUnit.SECONDS);
}
}
public void putHashRaw(String hashName, String key, String str) {
stringRedisTemplate.opsForHash().put(hashName, key, str);
}
public void putHashObj(String hashName, String key, Object obj, Integer expireSec) {
boolean hasKey = stringRedisTemplate.hasKey(key);
stringRedisTemplate.opsForHash().put(hashName, key, JSONObject.toJSONString(obj));
if (!hasKey) {
stringRedisTemplate.expire(key, expireSec, TimeUnit.SECONDS);
}
}
public void delHashObj(String hashName, String key) {
stringRedisTemplate.opsForHash().delete(hashName, key);
}
public void putRaw(String key, String value) {
putRaw(key, value, null);
}
public void putRaw(String key, String value, Integer expireSec) {
if (expireSec != null) {
stringRedisTemplate.opsForValue().set(key, value, expireSec, TimeUnit.SECONDS);
} else {
stringRedisTemplate.opsForValue().set(key, value);
}
}
public String getRaw(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
public void del(String key) {
stringRedisTemplate.delete(key);
}
public boolean hasKey(String key) {
return stringRedisTemplate.hasKey(key);
}
public void putSetRaw(String key, String member, Integer expireSec) {
stringRedisTemplate.opsForSet().add(key, member);
stringRedisTemplate.expire(key, expireSec, TimeUnit.SECONDS);
}
public void putSetRawAll(String key, String[] set, Integer expireSec) {
stringRedisTemplate.opsForSet().add(key, set);
stringRedisTemplate.expire(key, expireSec, TimeUnit.SECONDS);
}
public void removeSetRaw(String key, String member) {
stringRedisTemplate.opsForSet().remove(key, member);
}
public boolean isSetMember(String key, String member) {
return stringRedisTemplate.opsForSet().isMember(key, member);
}
/**
* 获取指定前缀的Key
*
* @param prefix
* @return
*/
public Set<String> getPrefixKeySet(String prefix) {
return stringRedisTemplate.keys(prefix + "*");
}
public void delPrefixKey(String prefix) {
Set<String> prefixKeySet = getPrefixKeySet(prefix);
for (String key : prefixKeySet) {
stringRedisTemplate.delete(key);
}
}
}
19
Source : RateLimiterAspect.java
with Apache License 2.0
from zhengkaixing
with Apache License 2.0
from zhengkaixing
/**
* <p>
* 限流切面
* </p>
*
* @author fy
* @date Created in 2020/3/7 10:31
*/
@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public clreplaced RateLimiterAspect {
private final static String SEPARATOR = ":";
private final static String REDIS_LIMIT_KEY_PREFIX = "limit:";
private final StringRedisTemplate stringRedisTemplate;
private final RedisScript<Long> limitRedisScript;
@Pointcut("@annotation(com.kxmall.market.core.ratelimit.annotation.RateLimiter)")
public void rateLimit() {
}
@Around("rateLimit()")
public Object pointcut(ProceedingJoinPoint point) throws Throwable {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
// 通过 AnnotationUtils.findAnnotation 获取 RateLimiter 注解
RateLimiter rateLimiter = AnnotationUtils.findAnnotation(method, RateLimiter.clreplaced);
if (rateLimiter != null) {
String key = rateLimiter.key();
// 默认用类名+方法名做限流的 key 前缀
if (StrUtil.isBlank(key)) {
// key = method.getDeclaringClreplaced().getName() + StrUtil.DOT + method.getName();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(method.getDeclaringClreplaced().getName()).append(StrUtil.DOT).append(method.getName());
// 此时考虑局域网多用户访问的情况,因此 key 需要加上方法参数更加合理
List<String> paramList = new ArrayList<>();
List<String> collectParams = argsToStrList(point.getArgs());
if (collectParams != null) {
paramList.addAll(collectParams);
}
key = String.format("%s{%s}", stringBuilder.toString(), String.join("&", paramList));
// TODO 考虑用户ID
}
// 最终限流的 key 为 前缀 + IP地址
key = key + SEPARATOR + IpUtil.getIpAddr();
long max = rateLimiter.max();
long timeout = rateLimiter.timeout();
TimeUnit timeUnit = rateLimiter.timeUnit();
boolean limited = shouldLimited(key, max, timeout, timeUnit);
if (limited) {
throw new AppServiceException(ExceptionDefinition.OPERATION_TOO_OFTEN);
}
}
return point.proceed();
}
private boolean shouldLimited(String key, long max, long timeout, TimeUnit timeUnit) {
// 最终的 key 格式为:
// limit:自定义key:IP
// limit:类名.方法名:IP
key = REDIS_LIMIT_KEY_PREFIX + key;
// 统一使用单位毫秒
long ttl = timeUnit.toMillis(timeout);
// 当前时间毫秒数
long now = Instant.now().toEpochMilli();
long expired = now - ttl;
// 注意这里必须转为 String,否则会报错 java.lang.Long cannot be cast to java.lang.String
Long executeTimes = stringRedisTemplate.execute(limitRedisScript, Collections.singletonList(key), now + "", ttl + "", expired + "", max + "");
if (executeTimes != null) {
if (executeTimes == 0) {
log.error("【{}】在单位时间 {} 毫秒内已达到访问上限,当前接口上限 {}", key, ttl, max);
return true;
} else {
log.info("【{}】在单位时间 {} 毫秒内访问 {} 次", key, ttl, executeTimes);
return false;
}
}
return false;
}
public static List<String> argsToStrList(Object... args) {
if (args != null && args.length > 0) {
List<String> collectParams = new LinkedList<>();
for (Object param : args) {
if (param != null) {
collectParams.add(String.valueOf(param));
}
}
if (collectParams.size() > 0) {
return collectParams;
}
}
return null;
}
}
19
Source : UserServiceImpl.java
with Apache License 2.0
from zhengkaixing
with Apache License 2.0
from zhengkaixing
/**
* Created by admin on 2019/6/30.
*/
@Service
public clreplaced UserServiceImpl implements UserService {
private static final String VERIFY_CODE_PREFIX = "VERIFY_CODE_";
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.clreplaced);
@Autowired
private UserMapper userMapper;
@Autowired
private SMSClient smsClient;
@Autowired
private CacheComponent cacheComponent;
@Autowired
private UserBizService userBizService;
@Autowired
private StringRedisTemplate userRedisTemplate;
@Autowired
private ActivityBizService activityBizService;
private OkHttpClient okHttpClient = new OkHttpClient();
@Value("${com.kxmall.market.wx.mini.app-id}")
private String wxMiNiAppid;
@Value("${com.kxmall.market.wx.mini.app-secret}")
private String wxMiNiSecret;
@Value("${com.kxmall.market.wx.app.app-id}")
private String wxAppAppid;
@Value("${com.kxmall.market.wx.app.app-secret}")
private String wxAppSecret;
@Value("${com.kxmall.market.wx.h5.app-id}")
private String wxH5Appid;
@Value("${com.kxmall.market.wx.h5.app-secret}")
private String wxH5Secret;
@Override
public String sendVerifyCode(String phone) throws ServiceException {
String verifyCode = GeneratorUtil.genSixVerifyCode();
boolean successFlag = SmsbaoSMSClient.senderSms(phone, verifyCode);
if (successFlag) {
cacheComponent.putRaw(VERIFY_CODE_PREFIX + phone, verifyCode, 300);
return "ok";
} else {
throw new AppServiceException(ExceptionDefinition.USER_SEND_VERIFY_FAILED);
}
// SMSResult res = smsClient.sendRegisterVerify(phone, verifyCode);
// if (res.isSucc()) {
// cacheComponent.putRaw(VERIFY_CODE_PREFIX + phone, verifyCode, 300);
// return "ok";
// } else {
// throw new AppServiceException(res.getMsg(), ExceptionDefinition.USER_SEND_VERIFY_FAILED.getCode());
// }
}
@Override
@Transactional(rollbackFor = Exception.clreplaced)
public UserDTO phoneLoginOrRegister(String phone, String verifyCode, String ip, String openId, String p) throws ServiceException {
// 1.校验验证码
checkVerifyCode(phone, verifyCode);
// 2.校验用户是否存在
UserDO userDO;
Date now = new Date();
List<UserDO> UserDOByPhoneList = userMapper.selectList(new EnreplacedyWrapper<UserDO>().eq("phone", phone));
if (UserDOByPhoneList == null || UserDOByPhoneList.size() == 0) {
// 注册
UserDO newUserDO = new UserDO();
newUserDO.setLoginType(UserLoginType.REGISTER.getCode());
newUserDO.setLastLoginIp(ip);
newUserDO.setPhone(phone);
newUserDO.setGmtLastLogin(now);
newUserDO.setOpenId(openId);
newUserDO.setGmtUpdate(now);
newUserDO.setGmtCreate(now);
userMapper.insert(newUserDO);
// 这一步是为了封装上数据库上配置的默认值
userDO = userMapper.selectById(newUserDO.getId());
} else {
// 登录
userDO = UserDOByPhoneList.get(0);
if (userDO.getStatus() == 0) {
throw new AppServiceException(ExceptionDefinition.USER_CAN_NOT_ACTICE);
}
UserDO userUpdateDO = new UserDO();
userUpdateDO.setId(userDO.getId());
userUpdateDO.setGmtLastLogin(now);
userUpdateDO.setLastLoginIp(ip);
userMapper.updateById(userUpdateDO);
}
String accessToken = GeneratorUtil.genSessionId();
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(userDO, userDTO);
userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(userDTO));
userDTO.setAccessToken(accessToken);
cacheComponent.del(VERIFY_CODE_PREFIX + phone);
// 邀请新人
Boolean flag = activityBizService.newRegistration(userDTO.getId(), p, ip);
if (flag) {
// 如果发券成功着更新数据库
UserDO updateUser = new UserDO();
updateUser.setId(userDTO.getId());
updateUser.setOldMan(true);
userMapper.updateById(updateUser);
}
return userDTO;
}
@Override
@Transactional
public String register(String phone, String preplacedword, String verifyCode, String ip) throws ServiceException {
// 1.校验验证码
checkVerifyCode(phone, verifyCode);
// 2.校验用户是否存在
Integer count = userMapper.selectCount(new EnreplacedyWrapper<UserDO>().eq("phone", phone));
if (count > 0) {
throw new AppServiceException(ExceptionDefinition.USER_PHONE_HAS_EXISTED);
}
// 3.校验成功,注册用户
Date now = new Date();
UserDO userDO = new UserDO();
userDO.setPhone(phone);
userDO.setPreplacedword(Md5Crypt.md5Crypt(preplacedword.getBytes(), "$1$" + phone.substring(0, 7)));
userDO.setLastLoginIp(ip);
userDO.setGmtLastLogin(now);
userDO.setGmtUpdate(now);
userDO.setGmtCreate(now);
userDO.setLoginType(UserLoginType.REGISTER.getCode());
userMapper.insert(userDO);
// 返回用户DTO
cacheComponent.del(VERIFY_CODE_PREFIX + phone);
return null;
}
@Override
@Transactional(rollbackFor = Exception.clreplaced)
public String bindPhone(String phone, String preplacedword, String verifyCode, Long userId) throws ServiceException {
// 1.校验验证码
checkVerifyCode(phone, verifyCode);
// 2.校验用户是否存在
Integer count = userMapper.selectCount(new EnreplacedyWrapper<UserDO>().eq("phone", phone));
if (count > 0) {
throw new AppServiceException(ExceptionDefinition.USER_PHONE_HAS_EXISTED);
}
// 3.校验成功,绑定手机
UserDO updateUserDO = new UserDO();
updateUserDO.setId(userId);
updateUserDO.setPhone(phone);
updateUserDO.setGmtUpdate(new Date());
if (userMapper.updateById(updateUserDO) > 0) {
cacheComponent.del(VERIFY_CODE_PREFIX + phone);
return "ok";
}
throw new AppServiceException(ExceptionDefinition.USER_UNKNOWN_EXCEPTION);
}
@Override
@Transactional(rollbackFor = Exception.clreplaced)
public String resetPreplacedword(String phone, String preplacedword, String verifyCode) throws ServiceException {
// 1.校验验证码
checkVerifyCode(phone, verifyCode);
// 2.校验用户是否存在
List<UserDO> targetUserList = userMapper.selectList(new EnreplacedyWrapper<UserDO>().eq("phone", phone));
if (CollectionUtils.isEmpty(targetUserList)) {
throw new AppServiceException(ExceptionDefinition.USER_PHONE_NOT_EXIST);
}
Long id = targetUserList.get(0).getId();
// 3.校验成功,重置密码
UserDO updateUserDO = new UserDO();
updateUserDO.setId(id);
updateUserDO.setPreplacedword(Md5Crypt.md5Crypt(preplacedword.getBytes(), "$1$" + phone.substring(0, 7)));
updateUserDO.setGmtUpdate(new Date());
if (userMapper.updateById(updateUserDO) > 0) {
cacheComponent.del(VERIFY_CODE_PREFIX + phone);
return "ok";
}
throw new AppServiceException(ExceptionDefinition.USER_UNKNOWN_EXCEPTION);
}
/**
* 验证码抽取校验
*
* @param phone
* @param verifyCode
* @throws ServiceException
*/
private void checkVerifyCode(String phone, String verifyCode) throws ServiceException {
String raw = cacheComponent.getRaw(VERIFY_CODE_PREFIX + phone);
if (StringUtils.isEmpty(raw)) {
throw new AppServiceException(ExceptionDefinition.USER_VERIFY_CODE_NOT_EXIST);
}
if (!raw.equals(verifyCode)) {
throw new AppServiceException(ExceptionDefinition.USER_VERIFY_CODE_NOT_CORRECT);
}
}
@Override
@Transactional
public UserDTO login(String phone, String preplacedword, Integer loginType, String raw, String ip) throws ServiceException {
String cryptPreplacedword = Md5Crypt.md5Crypt(preplacedword.getBytes(), "$1$" + phone.substring(0, 7));
UserDTO userDTO = userMapper.login(phone, cryptPreplacedword);
if (userDTO == null) {
throw new AppServiceException(ExceptionDefinition.USER_PHONE_OR_PreplacedWORD_NOT_CORRECT);
}
// 检查帐号是否已经冻结
if (userDTO.getStatus() == 0) {
throw new AppServiceException(ExceptionDefinition.USER_CAN_NOT_ACTICE);
}
if (!StringUtils.isEmpty(raw) && UserLoginType.contains(loginType)) {
if (loginType == UserLoginType.MP_WEIXIN.getCode()) {
try {
JSONObject thirdPartJsonObject = JSONObject.parseObject(raw);
String code = thirdPartJsonObject.getString("code");
String body = okHttpClient.newCall(new Request.Builder().url("https://api.weixin.qq.com/sns/jscode2session?appid=" + (UserLoginType.MP_WEIXIN.getCode() == loginType ? wxMiNiAppid : wxAppAppid) + "&secret=" + (UserLoginType.MP_WEIXIN.getCode() == loginType ? wxMiNiSecret : wxAppSecret) + "&grant_type=authorization_code&js_code=" + code).get().build()).execute().body().string();
JSONObject jsonObject = JSONObject.parseObject(body);
Integer errcode = jsonObject.getInteger("errcode");
if (errcode == null || errcode == 0) {
String miniOpenId = jsonObject.getString("openid");
// 将此次登录的openId,暂且放入user的域里面,支付的时候会用到
userDTO.setLoginType(loginType);
userDTO.setOpenId(miniOpenId);
}
} catch (Exception e) {
logger.error("[微信第三方登录] 异常", e);
throw new ThirdPartServiceException(ExceptionDefinition.THIRD_PART_SERVICE_EXCEPTION.getMsg(), ExceptionDefinition.THIRD_PART_SERVICE_EXCEPTION.getCode());
}
}
}
String accessToken = GeneratorUtil.genSessionId();
// 放入SESSION专用Redis数据源中
userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(userDTO));
userDTO.setAccessToken(accessToken);
UserDO userUpdateDO = new UserDO();
userUpdateDO.setId(userDTO.getId());
userUpdateDO.setGmtLastLogin(new Date());
userUpdateDO.setLastLoginIp(ip);
userMapper.updateById(userUpdateDO);
return userDTO;
}
@Override
@Transactional(rollbackFor = Exception.clreplaced)
public UserDTO authPhone(String encryptedData, String iv, Integer loginType, String session_key, String openId, String p, String ip) throws ServiceException {
try {
String result = WxUtil.wxDecrypt(encryptedData, session_key, iv);
JSONObject json = JSONObject.parseObject(result);
if (org.apache.commons.lang3.StringUtils.isNoneBlank(result) && json.containsKey("phoneNumber")) {
String phone = json.getString("phoneNumber");
// String appid = json.getJSONObject("watermark").getString("appid");
if (org.apache.commons.lang3.StringUtils.isNoneBlank(phone)) {
UserDO userDO;
List<UserDO> userDOS = userMapper.selectList(new EnreplacedyWrapper<UserDO>().eq("phone", phone).eq("login_type", loginType));
if (CollectionUtils.isEmpty(userDOS)) {
// 新用户绑定手机号
Date now = new Date();
UserDO newUserDO = new UserDO();
newUserDO.setLoginType(loginType);
newUserDO.setOpenId(openId);
newUserDO.setLastLoginIp(ip);
newUserDO.setPhone(phone);
newUserDO.setGmtLastLogin(now);
newUserDO.setGmtUpdate(now);
newUserDO.setGmtCreate(now);
userMapper.insert(newUserDO);
// 这一步是为了封装上数据库上配置的默认值
userDO = userMapper.selectById(newUserDO.getId());
} else {
// 老用户
userDO = userDOS.get(0);
UserDO userUpdateDO = new UserDO();
userUpdateDO.setId(userDO.getId());
userUpdateDO.setOpenId(openId);
userUpdateDO.setGmtLastLogin(new Date());
userUpdateDO.setLastLoginIp(ip);
userMapper.updateById(userUpdateDO);
}
// 检查帐号是否已经冻结
if (userDO.getStatus() == 0) {
throw new AppServiceException(ExceptionDefinition.USER_CAN_NOT_ACTICE);
}
String accessToken = GeneratorUtil.genSessionId();
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(userDO, userDTO);
userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(userDTO));
userDTO.setSessionKey(session_key);
userDTO.setAccessToken(accessToken);
Boolean flag = activityBizService.newRegistration(userDO.getId(), p, ip);
if (flag) {
// 如果发券成功着更新数据库
UserDO updateUser = new UserDO();
updateUser.setId(userDO.getId());
updateUser.setOldMan(true);
userMapper.updateById(updateUser);
}
return userDTO;
} else {
throw new AppServiceException(ExceptionDefinition.USER_PHONE_NOT_BINDING_WX);
}
} else {
throw new AppServiceException(ExceptionDefinition.USER_WX_PHONE_PARSER_ERROR);
}
} catch (Exception e) {
logger.error(" [微信授权手机号失败]", e);
throw new AppServiceException(ExceptionDefinition.USER_WX_AUTH_PHONE);
}
}
@Override
public String logout(String accessToken, Long userId) throws ServiceException {
userRedisTemplate.delete(accessToken);
return "ok";
}
@Override
public UserDTO thirdPartLogin(Integer loginType, String ip, String raw) throws ServiceException {
try {
if (UserLoginType.MP_WEIXIN.getCode() == loginType) {
return wechatLogin(loginType, ip, raw);
} else if (UserLoginType.H5_WEIXIN.getCode() == loginType) {
// H5 微信公众号网页登录
String json = okHttpClient.newCall(new Request.Builder().url("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxH5Appid + "&secret=" + wxH5Secret + "&code=" + raw + "&grant_type=authorization_code").build()).execute().body().string();
JSONObject jsonObject = JSONObject.parseObject(json);
Integer errcode = jsonObject.getInteger("errcode");
if (errcode == null || errcode == 0) {
String openid = jsonObject.getString("openid");
List<UserDO> userDOS = userMapper.selectList(new EnreplacedyWrapper<UserDO>().eq("open_id", openid).eq("login_type", loginType));
if (!CollectionUtils.isEmpty(userDOS)) {
// 若用户已经注册,则直接返回用户
String accessToken = GeneratorUtil.genSessionId();
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(userDOS.get(0), userDTO);
userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(userDTO));
userDTO.setAccessToken(accessToken);
return userDTO;
} else {
String userAccessToken = jsonObject.getString("access_token");
// 通过用户AccessToken换取用户信息
String userInfoJson = okHttpClient.newCall(new Request.Builder().url("https://api.weixin.qq.com/sns/userinfo?access_token=" + userAccessToken + "&openid=" + openid + "&lang=zh_CN").build()).execute().body().string();
JSONObject userInfoJsonObject = JSONObject.parseObject(userInfoJson);
Date now = new Date();
UserDO newUserDO = new UserDO();
newUserDO.setLoginType(loginType);
newUserDO.setNickname(userInfoJsonObject.getString("nickname"));
newUserDO.setAvatarUrl(userInfoJsonObject.getString("headimgurl"));
newUserDO.setGender(userInfoJsonObject.getInteger("sex"));
newUserDO.setOpenId(openid);
newUserDO.setLastLoginIp(ip);
newUserDO.setGmtLastLogin(now);
newUserDO.setGmtUpdate(now);
newUserDO.setGmtCreate(now);
userMapper.insert(newUserDO);
// 这一步是为了封装上数据库上配置的默认值
UserDO userDO = userMapper.selectById(newUserDO.getId());
String accessToken = GeneratorUtil.genSessionId();
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(userDO, userDTO);
userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(userDTO));
userDTO.setAccessToken(accessToken);
return userDTO;
}
} else {
throw new AppServiceException(ExceptionDefinition.USER_THIRD_PART_LOGIN_FAILED);
}
} else if (UserLoginType.APP_WEIXIN.getCode() == loginType) {
// return wechatLogin(loginType, ip, raw);
// UNI-APP 的 微信APP登录 APPSecret是保存在前端的。这点非常不安全。但是用了他的框架,也没有办法
JSONObject jsonObject = JSONObject.parseObject(raw);
JSONObject authResult = jsonObject.getJSONObject("authResult");
String openid = authResult.getString("openid");
// String openid = "osTQe6L_JOoJkrMO1vAT_peMivjA";
List<UserDO> userDOS = userMapper.selectList(new EnreplacedyWrapper<UserDO>().eq("open_id", openid).eq("login_type", loginType));
UserDO userDO;
if (CollectionUtils.isEmpty(userDOS)) {
// 创建新用户
Date now = new Date();
UserDO newUserDO = new UserDO();
newUserDO.setLoginType(loginType);
newUserDO.setOpenId(openid);
newUserDO.setLastLoginIp(ip);
newUserDO.setGmtLastLogin(now);
newUserDO.setGmtUpdate(now);
newUserDO.setGmtCreate(now);
userMapper.insert(newUserDO);
// 这一步是为了封装上数据库上配置的默认值
userDO = userMapper.selectById(newUserDO.getId());
} else {
userDO = userDOS.get(0);
UserDO userUpdateDO = new UserDO();
userUpdateDO.setId(userDO.getId());
userUpdateDO.setGmtLastLogin(new Date());
userUpdateDO.setLastLoginIp(ip);
userMapper.updateById(userUpdateDO);
}
// 检查帐号是否已经冻结
if (userDO.getStatus() == 0) {
throw new AppServiceException(ExceptionDefinition.USER_CAN_NOT_ACTICE);
}
String accessToken = GeneratorUtil.genSessionId();
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(userDO, userDTO);
userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(userDTO));
userDTO.setAccessToken(accessToken);
return userDTO;
} else {
throw new AppServiceException(ExceptionDefinition.USER_THIRD_PART_NOT_SUPPORT);
}
} catch (ServiceException e) {
throw e;
} catch (Exception e) {
logger.error("[用户第三方登录] 异常", e);
throw new AppServiceException(ExceptionDefinition.USER_THIRD_PART_LOGIN_FAILED);
}
}
/**
* 微信第三方登录 抽取接口(目前只有小程序)
*
* @param loginType
* @param ip
* @param raw
* @return
* @throws Exception
*/
private UserDTO wechatLogin(Integer loginType, String ip, String raw) throws Exception {
// 微信第三方登录
JSONObject thirdPartJsonObject = JSONObject.parseObject(raw);
String code = thirdPartJsonObject.getString("code");
String body = okHttpClient.newCall(new Request.Builder().url("https://api.weixin.qq.com/sns/jscode2session?appid=" + (UserLoginType.MP_WEIXIN.getCode() == loginType ? wxMiNiAppid : wxAppAppid) + "&secret=" + (UserLoginType.MP_WEIXIN.getCode() == loginType ? wxMiNiSecret : wxAppSecret) + "&grant_type=authorization_code&js_code=" + code).get().build()).execute().body().string();
JSONObject jsonObject = JSONObject.parseObject(body);
Integer errcode = jsonObject.getInteger("errcode");
if (errcode == null || errcode == 0) {
String miniOpenId = jsonObject.getString("openid");
String sessionKey = jsonObject.getString("session_key");
List<UserDO> userDOS = userMapper.selectList(new EnreplacedyWrapper<UserDO>().eq("open_id", miniOpenId).eq("login_type", loginType));
UserDO userDO;
if (CollectionUtils.isEmpty(userDOS) || (userDOS != null && StringUtils.isEmpty(userDOS.get(0).getPhone()))) {
// 若用户为空,则注册此用户
UserDTO userDTO = new UserDTO();
userDTO.setOpenId(miniOpenId);
userDTO.setLoginType(loginType);
userDTO.setSessionKey(sessionKey);
return userDTO;
} else {
// 已经注册的用户
userDO = userDOS.get(0);
UserDO userUpdateDO = new UserDO();
userUpdateDO.setId(userDO.getId());
userUpdateDO.setGmtLastLogin(new Date());
userUpdateDO.setLastLoginIp(ip);
userMapper.updateById(userUpdateDO);
// 检查帐号是否已经冻结
if (userDO.getStatus() == 0) {
throw new AppServiceException(ExceptionDefinition.USER_CAN_NOT_ACTICE);
}
String accessToken = GeneratorUtil.genSessionId();
UserDTO userDTO = new UserDTO();
BeanUtils.copyProperties(userDO, userDTO);
userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(userDTO));
userDTO.setSessionKey(sessionKey);
userDTO.setAccessToken(accessToken);
return userDTO;
}
} else {
logger.info("[微信登录] 回复失败 回复报文:" + body);
throw new AppServiceException(ExceptionDefinition.USER_THIRD_UNEXPECT_RESPONSE);
}
}
@Override
public String syncUserInfo(String nickName, String nickname, String avatarUrl, Integer gender, Long birthday, String accessToken, Long userId) throws ServiceException {
UserDO updateUserDO = new UserDO();
updateUserDO.setId(userId);
updateUserDO.setNickname(StringUtils.isEmpty(nickName) ? nickname : nickName);
updateUserDO.setAvatarUrl(avatarUrl);
updateUserDO.setGender(gender);
updateUserDO.setGmtUpdate(new Date());
if (birthday != null)
updateUserDO.setBirthday(new Date(birthday));
if (userMapper.updateById(updateUserDO) > 0) {
// 更新SESSION缓存
UserDTO user = SessionUtil.getUser();
if (!StringUtils.isEmpty(nickName)) {
user.setNickname(nickName);
}
if (!StringUtils.isEmpty(avatarUrl)) {
user.setAvatarUrl(avatarUrl);
}
if (birthday != null) {
user.setBirthday(new Date(birthday));
}
if (gender != null) {
user.setGender(gender);
}
userRedisTemplate.opsForValue().set(Const.USER_REDIS_PREFIX + accessToken, JSONObject.toJSONString(user));
return "ok";
}
throw new AppServiceException(ExceptionDefinition.USER_UNKNOWN_EXCEPTION);
}
@Override
public Object getH5Sign(String url) throws ServiceException {
try {
String wxH5AccessToken = userBizService.getWxH5AccessToken();
// 我也不知道为什么微信这里要换两次
String wxH5Ticket = userBizService.getWxH5Ticket(wxH5AccessToken);
String noncestr = GeneratorUtil.genUUId();
long timestamp = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
sb.append("jsapi_ticket=");
sb.append(wxH5Ticket);
sb.append("&noncestr=");
sb.append(noncestr);
sb.append("×tamp=");
sb.append(timestamp);
sb.append("&url=");
sb.append(url);
// 明文
String content = sb.toString();
String signature = SHAUtil.shaEncode(content);
Map<String, Object> obj = new HashMap<>();
obj.put("noncestr", noncestr);
obj.put("timestamp", timestamp);
obj.put("sign", signature);
return obj;
} catch (Exception e) {
logger.info("[获取H5签名] 异常", e);
throw new AppServiceException(ExceptionDefinition.APP_UNKNOWN_EXCEPTION);
}
}
}
19
Source : ApiController.java
with Apache License 2.0
from zhengkaixing
with Apache License 2.0
from zhengkaixing
/**
* Description:
* User: admin
* Date: 2018-08-08
* Time: 下午11:00
*/
@Controller
@RequestMapping("/m.api")
public clreplaced ApiController {
private static final Logger logger = LoggerFactory.getLogger(ApiController.clreplaced);
private static final Integer USER_ACCESS_TOKEN_TIMEOUT = 60 * 24 * 3;
private static final Integer ADMIN_ACCESS_TOKEN_TIMEOUT = 60 * 12;
@Autowired
private ApplicationContext applicationContext;
@Autowired
private StringRedisTemplate userRedisTemplate;
@Value("${com.kxmall.market.env}")
private String ENV;
@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public String invoke(HttpServletRequest req, HttpServletResponse res) {
long invokeTime = System.currentTimeMillis();
try {
logger.info("[用户请求] request=" + JSONObject.toJSONString(req.getParameterMap()));
Object obj = process(req, res, invokeTime);
if (Const.IGNORE_PARAM_LIST.contains(obj.getClreplaced())) {
return obj.toString();
}
String result = JSONObject.toJSONString(obj);
long during = System.currentTimeMillis() - invokeTime;
// if (during > 1000) {
// logger.info("[用户请求] 慢接口");
// }
logger.info("[用户请求] 用时 " + during + "ms, response=" + JSONObject.toJSONString(result));
return result;
} catch (ServiceException e) {
GatewayResponse gatewayResponse = new GatewayResponse();
gatewayResponse.setTimestamp(invokeTime);
gatewayResponse.setErrno(e.getCode());
gatewayResponse.setErrmsg(e.getMessage());
String result = JSONObject.toJSONString(gatewayResponse);
long during = System.currentTimeMillis() - invokeTime;
logger.info("[用户请求] 用时 " + during + "ms, response=" + JSONObject.toJSONString(result));
return result;
}
}
private Object process(HttpServletRequest request, HttpServletResponse response, long invokeTime) throws ServiceException {
try {
ApiManager apiManager = applicationContext.getBean(ApiManager.clreplaced);
Map<String, String[]> parameterMap = request.getParameterMap();
String[] gps = parameterMap.get("_gp");
String[] mts = parameterMap.get("_mt");
if (gps == null || mts == null || gps.length == 0 || mts.length == 0) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_API_NOT_EXISTS);
}
String _gp = gps[0];
String _mt = mts[0];
String[] _types = parameterMap.get("_type");
String _type = null;
if (_types != null && _types.length > 0) {
_type = _types[0];
}
Method method = apiManager.getMethod(_gp, _mt);
if (method == null) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_API_NOT_EXISTS);
}
HttpMethod httpMethod = method.getAnnotation(HttpMethod.clreplaced);
if (httpMethod == null) {
// 只起标记作用防止调到封闭方法了
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_API_NOT_EXISTS);
}
String permission = httpMethod.permission();
if (!StringUtils.isEmpty(permission)) {
// 若需要权限,则校验当前用户是否具有权限
String accessToken = request.getHeader(Const.ADMIN_ACCESS_TOKEN);
String admin = userRedisTemplate.opsForValue().get(Const.ADMIN_REDIS_PREFIX + accessToken);
/*if (StringUtils.isEmpty(admin)) {
throw new LauncherServiceException(LauncherExceptionDefinition.LAUNCHER_ADMIN_NOT_LOGIN);
}*/
AdminDTO adminDTO = JSONObject.parseObject(admin, AdminDTO.clreplaced);
SessionUtil.setAdmin(adminDTO);
/*if (!SessionUtil.hasPerm(permission)) {
throw new LauncherServiceException(LauncherExceptionDefinition.LAUNCHER_ADMIN_PERMISSION_DENY);
}*/
}
Object serviceBean = applicationContext.getBean(method.getDeclaringClreplaced());
Parameter[] methodParameters = method.getParameters();
Object[] args = new Object[methodParameters.length];
for (int i = 0; i < methodParameters.length; i++) {
Parameter methodParam = methodParameters[i];
HttpParam httpParam = methodParam.getAnnotation(HttpParam.clreplaced);
if (httpParam == null) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_API_NOT_EXISTS);
}
if (httpParam.type() == HttpParamType.COMMON) {
String[] paramArray = parameterMap.get(httpParam.name());
if (paramArray != null && paramArray.length > 0 && !StringUtils.isEmpty(paramArray[0])) {
Clreplaced<?> type = methodParam.getType();
// 参数校验
checkParam(type, methodParam, paramArray[0]);
if (String.clreplaced == type) {
args[i] = paramArray[0];
} else if (Const.IGNORE_PARAM_LIST.contains(type)) {
Constructor<?> constructor = type.getConstructor(String.clreplaced);
args[i] = constructor.newInstance(paramArray[0]);
} else if (type.isArray()) {
// 若是数组
Clreplaced<?> itemType = type.getComponentType();
Object[] realType = (Object[]) Array.newInstance(itemType, paramArray.length);
if (paramArray.length > 0) {
for (int j = 0; j < paramArray.length; j++) {
if (Const.IGNORE_PARAM_LIST.contains(itemType)) {
Constructor<?> constructor = itemType.getConstructor(String.clreplaced);
realType[j] = constructor.newInstance(paramArray[j]);
} else {
realType[j] = JSONObject.parseObject(paramArray[j], itemType);
}
}
}
args[i] = realType;
} else {
// Json解析
args[i] = JSONObject.parseObject(paramArray[0], type);
}
} else {
if (!StringUtils.isEmpty(httpParam.valueDef())) {
// 若有默认值
Clreplaced<?> type = methodParam.getType();
Constructor<?> constructor = type.getConstructor(String.clreplaced);
args[i] = constructor.newInstance(httpParam.valueDef());
} else {
if (methodParam.getAnnotation(NotNull.clreplaced) != null) {
logger.error("missing :" + httpParam.name());
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
args[i] = null;
}
}
} else if (httpParam.type() == HttpParamType.USER_ID) {
String accessToken = request.getHeader(Const.USER_ACCESS_TOKEN);
if (!StringUtils.isEmpty(accessToken)) {
String userJson = userRedisTemplate.opsForValue().get(Const.USER_REDIS_PREFIX + accessToken);
if (!StringUtils.isEmpty(userJson)) {
UserDTO userDTO = JSONObject.parseObject(userJson, UserDTO.clreplaced);
SessionUtil.setUser(userDTO);
args[i] = userDTO.getId();
userRedisTemplate.expire(Const.USER_REDIS_PREFIX + accessToken, USER_ACCESS_TOKEN_TIMEOUT, TimeUnit.MINUTES);
continue;
}
}
// if (args[i] == null && methodParam.getAnnotation(NotNull.clreplaced) != null) {
// throw new LauncherServiceException(LauncherExceptionDefinition.LAUNCHER_USER_NOT_LOGIN);
// }
} else if (httpParam.type() == HttpParamType.ADMIN_ID) {
String accessToken = request.getHeader(Const.ADMIN_ACCESS_TOKEN);
if (!StringUtils.isEmpty(accessToken)) {
String userJson = userRedisTemplate.opsForValue().get(Const.ADMIN_REDIS_PREFIX + accessToken);
if (!StringUtils.isEmpty(userJson)) {
AdminDTO adminDTO = JSONObject.parseObject(userJson, AdminDTO.clreplaced);
SessionUtil.setAdmin(adminDTO);
args[i] = adminDTO.getId();
userRedisTemplate.expire(Const.ADMIN_REDIS_PREFIX + accessToken, ADMIN_ACCESS_TOKEN_TIMEOUT, TimeUnit.MINUTES);
continue;
}
}
/* if (args[i] == null && methodParam.getAnnotation(NotNull.clreplaced) != null) {
throw new LauncherServiceException(LauncherExceptionDefinition.LAUNCHER_ADMIN_NOT_LOGIN);
}*/
} else if (httpParam.type() == HttpParamType.IP) {
// 这里根据实际情况来定。 若使用了负载均衡,Ip将会被代理服务器设置到某个Header里面
args[i] = "27.10.60.71";
// if (ENV.equals("1")) {
// //若是开发环境
// args[i] = "27.10.60.71";
// } else {
// args[i] = request.getHeader("X-Forwarded-For");
// }
} else if (httpParam.type() == HttpParamType.HEADER) {
String header = request.getHeader(httpParam.name());
args[i] = header;
if (header == null && methodParam.getAnnotation(NotNull.clreplaced) != null) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
}
Object invokeObj = method.invoke(serviceBean, args);
ResultType resultType = httpMethod.type();
if (!StringUtils.isEmpty(_type) && "raw".equals(_type)) {
// 如果是不用包装的直接返回
return invokeObj;
}
// 下面是需要包装返回的
if (resultType == ResultType.COOKIE) {
// 加入Cookie时处理
if (StringUtils.isEmpty(httpMethod.retName())) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_API_NOT_EXISTS);
} else {
// setCookie
Cookie cookie = new Cookie(httpMethod.retName(), (String) invokeObj);
cookie.setPath("/");
if (httpMethod.maxAge() != -1) {
cookie.setMaxAge(httpMethod.maxAge());
}
response.addCookie(cookie);
}
}
GatewayResponse gatewayResponse = new GatewayResponse();
gatewayResponse.setErrno(200);
gatewayResponse.setErrmsg("成功");
gatewayResponse.setTimestamp(invokeTime);
gatewayResponse.setData(invokeObj);
return gatewayResponse;
} catch (MyselfPersistenceException e) {
throw new AdminServiceException((AdminExceptionDefinition.DEMO_MODE_NO_PERMISSION_OPERATION));
} catch (ServiceException e) {
throw e;
} catch (Exception e) {
if (e instanceof InvocationTargetException) {
InvocationTargetException proxy = (InvocationTargetException) e;
Throwable targetException = proxy.getTargetException();
if (targetException instanceof ServiceException) {
throw (ServiceException) targetException;
} else if (targetException.getCause() != null && targetException.getCause().getCause() instanceof MyselfPersistenceException) {
logger.error("[网关] 系统未知异常 MyselfPersistenceException", e);
throw new AdminServiceException((AdminExceptionDefinition.DEMO_MODE_NO_PERMISSION_OPERATION));
} else {
logger.error("[网关] 系统未知异常1", e);
if (StringUtils.isEmpty(targetException.getMessage())) {
throw new AdminServiceException(new ServiceExceptionDefinition(99999, "空指针异常!"));
}
throw new AdminServiceException(new ServiceExceptionDefinition(99999, targetException.getMessage()));
}
}
logger.error("[网关] 系统未知异常2", e);
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_UNKNOWN_EXCEPTION);
}
}
private void checkParam(Clreplaced<?> type, Parameter methodParam, String target) throws ServiceException {
if (type == String.clreplaced) {
TextFormat textFormat = methodParam.getAnnotation(TextFormat.clreplaced);
if (textFormat != null) {
String regex = textFormat.regex();
if (!StringUtils.isEmpty(regex)) {
// 如果正则生效,则直接使用正则校验
if (!target.matches(regex)) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
} else {
boolean notChinese = textFormat.notChinese();
if (notChinese) {
if (target.matches("[\\u4e00-\\u9fa5]+")) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
String[] contains = textFormat.contains();
for (int j = 0; j < contains.length; j++) {
if (!target.contains(contains[j])) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
String[] notContains = textFormat.notContains();
for (int j = 0; j < notContains.length; j++) {
if (target.contains(notContains[j])) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
String startWith = textFormat.startWith();
if (!StringUtils.isEmpty(startWith)) {
if (!target.startsWith(startWith)) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
String endsWith = textFormat.endsWith();
if (!StringUtils.isEmpty(target)) {
if (!target.endsWith(endsWith)) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
int targetLength = target.length();
int length = textFormat.length();
if (length != -1) {
if (targetLength != length) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
if (targetLength < textFormat.lengthMin()) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
if (targetLength > textFormat.lengthMax()) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
}
} else if (type == Integer.clreplaced) {
Range range = methodParam.getAnnotation(Range.clreplaced);
Integer integer = new Integer(target);
if (range != null) {
if (integer > range.max() || integer < range.min()) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
} else if (type == Long.clreplaced) {
Range range = methodParam.getAnnotation(Range.clreplaced);
if (range != null) {
Long integer = new Long(target);
if (integer > range.max() || integer < range.min()) {
throw new AdminServiceException(AdminExceptionDefinition.LAUNCHER_PARAM_CHECK_FAILED);
}
}
}
}
}
19
Source : RedisConfig.java
with Apache License 2.0
from zheng-zy
with Apache License 2.0
from zheng-zy
// RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
// configuration.prefixKeysWith("bda");
// configuration = configuration.entryTtl(Duration.ofMinutes(30));
// Set<String> cacheNames = new HashSet<>();
// cacheNames.add("test1");
// cacheNames.add("test2");
// Map<String, RedisCacheConfiguration> configurationMap = new HashMap<>(10);
// configurationMap.put("test1", configuration);
// configurationMap.put("test2", configuration.entryTtl(Duration.ofMinutes(60)));
// RedisCacheManager manager = RedisCacheManager.builder(factory)
// .initialCacheNames(cacheNames)
// .withInitialCacheConfigurations(configurationMap)
// .build();
// return manager;
private StringRedisTemplate getRedisTemplate() {
StringRedisTemplate template = new StringRedisTemplate();
template.setValueSerializer(new GenericFastJsonRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
19
Source : RedisConfig.java
with Apache License 2.0
from zheng-zy
with Apache License 2.0
from zheng-zy
@Bean(name = "redisTemplateB")
public StringRedisTemplate redisTemplateB(@Autowired @Qualifier("factoryB") LettuceConnectionFactory factoryB) {
StringRedisTemplate template = new StringRedisTemplate(factoryB);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.clreplaced);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 将类名称序列化到json串中
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
19
Source : RedisConfig.java
with Apache License 2.0
from zheng-zy
with Apache License 2.0
from zheng-zy
@Bean(name = "redisTemplateA")
public StringRedisTemplate redisTemplateA(LettuceConnectionFactory factoryA) {
StringRedisTemplate template = new StringRedisTemplate(factoryA);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.clreplaced);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setKeySerializer(redisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
19
Source : RedisConfig.java
with Apache License 2.0
from zheng-zy
with Apache License 2.0
from zheng-zy
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.clreplaced);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
19
Source : RedisController.java
with Apache License 2.0
from ZHENFENG13
with Apache License 2.0
from ZHENFENG13
@RestController
public clreplaced RedisController {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@GetMapping("/addStringToRedis")
@ResponseBody
public Boolean addStringToRedis(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
return true;
}
@GetMapping("/getStringFromRedis")
@ResponseBody
public String getStringFromRedis(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@GetMapping("/addUserToRedis")
@ResponseBody
public Boolean addUserToRedis(String name, String preplacedword) {
User user = new User();
user.setName(name);
user.setPreplacedword(preplacedword);
redisTemplate.opsForValue().set(name, user);
return true;
}
@GetMapping("/getUserFromRedis")
@ResponseBody
public User getUserFromRedis(String name) {
return (User) redisTemplate.opsForValue().get(name);
}
@GetMapping("/deleteUserFromRedis")
@ResponseBody
public Boolean deleteUserFromRedis(String name) {
return redisTemplate.delete(name);
}
}
19
Source : RedisWebSocketManager.java
with Apache License 2.0
from zhaowb82
with Apache License 2.0
from zhaowb82
/**
* WebSocket的session无法序列化,所以session还是保存在本地内存中,发送消息这种就走订阅发布模式
* 1.redis或者mq进行发布订阅,广播->有某个节点能找到此人就发送消息,其他的忽略
* 2.Nginx进行IP hash 可以使用{@link MemWebSocketManager}
* <p>
* 3.需要扩展不同的功能,就写相应的Action,放入容器中,然后给订阅的频道发布一条包含该Action的JSON串
*
* @author xiongshiyan at 2018/10/10 , contact me with email [email protected] or phone 15208384257
* @see RedisWebSocketManager#sendMessage
*/
public clreplaced RedisWebSocketManager extends MemWebSocketManager {
public static final String CHANNEL = "websocket";
private static final String COUNT_KEY = "RedisWebSocketManagerCountKey";
protected StringRedisTemplate stringRedisTemplate;
public RedisWebSocketManager(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
@Override
public void put(String identifier, WebSocket webSocket) {
super.put(identifier, webSocket);
// 在线数量加1
countChange(1);
}
@Override
public void remove(String identifier) {
boolean containsKey = localWebSocketMap().containsKey(identifier);
if (containsKey) {
super.remove(identifier);
} else {
Map<String, Object> map = new HashMap<>(2);
map.put(Action.ACTION, RemoveAction.clreplaced.getName());
map.put(Action.IDENTIFIER, identifier);
// 在websocket频道上发布发送消息的消息
stringRedisTemplate.convertAndSend(getChannel(), JSONObject.toJSONString(map));
}
// 在线数量减1
countChange(-1);
}
@Override
public int size() {
return getCount();
}
@Override
public void sendMessage(String identifier, String message) {
WebSocket webSocket = get(identifier);
// 本地能找到就直接发
if (null != webSocket) {
WebSocketUtil.sendMessage(webSocket.getSession(), message);
return;
}
Map<String, Object> map = new HashMap<>(3);
map.put(Action.ACTION, SendMessageAction.clreplaced.getName());
map.put(Action.IDENTIFIER, identifier);
map.put(Action.MESSAGE, message);
// 在websocket频道上发布发送消息的消息
stringRedisTemplate.convertAndSend(getChannel(), JSONObject.toJSONString(map));
}
@Override
public void broadcast(String message) {
Map<String, Object> map = new HashMap<>(2);
map.put(Action.ACTION, BroadCastAction.clreplaced.getName());
map.put(Action.MESSAGE, message);
// 在websocket频道上发布广播的消息
stringRedisTemplate.convertAndSend(getChannel(), JSONObject.toJSONString(map));
}
protected String getChannel() {
return CHANNEL;
}
/**
* 增减在线数量
*/
private void countChange(int delta) {
ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
// 获取在线当前数量
int count = getCount(value);
count = count + delta;
count = count > 0 ? count : 0;
// 设置新的数量
value.set(COUNT_KEY, "" + count);
}
/**
* 获取当前在线数量
*/
private int getCount() {
ValueOperations<String, String> value = stringRedisTemplate.opsForValue();
return getCount(value);
}
private int getCount(ValueOperations<String, String> value) {
String countStr = value.get(COUNT_KEY);
int count = 0;
if (null != countStr) {
count = Integer.parseInt(countStr);
}
return count;
}
}
19
Source : RedisUtil.java
with Apache License 2.0
from zhangdaiscott
with Apache License 2.0
from zhangdaiscott
/**
* redis 工具类
* @Author Scott
*/
@Component
public clreplaced RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param by 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param by 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
19
Source : AuthStateRedisCache.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* auth state redis cache, 适用单机与分布式
* @author YongWu zheng
* @version V1.0 Created by 2020/10/6 19:22
*/
public clreplaced AuthStateRedisCache implements Auth2StateCache {
private final StringRedisTemplate stringRedisTemplate;
private final Duration timeout;
private final String cacheKeyPrefix;
public AuthStateRedisCache(Auth2Properties auth2Properties, Object stringRedisTemplate) {
this.stringRedisTemplate = (StringRedisTemplate) stringRedisTemplate;
final JustAuthProperties justAuth = auth2Properties.getJustAuth();
this.timeout = justAuth.getTimeout();
this.cacheKeyPrefix = justAuth.getCacheKeyPrefix();
}
@Override
public void cache(String key, String value) {
stringRedisTemplate.opsForValue().set(parsingKey(key), value, this.timeout);
}
@Override
public void cache(String key, String value, long timeout) {
stringRedisTemplate.opsForValue().set(parsingKey(key), value, timeout, TimeUnit.MILLISECONDS);
}
@Override
public String get(String key) {
return stringRedisTemplate.opsForValue().get(parsingKey(key));
}
@Override
public boolean containsKey(String key) {
return StringUtils.hasText(stringRedisTemplate.opsForValue().get(parsingKey(key)));
}
@Override
public CacheKeyStrategy getCacheKeyStrategy() {
return CacheKeyStrategy.UUID;
}
private String parsingKey(String key) {
return this.cacheKeyPrefix + key;
}
}
19
Source : UmsTenantContextHolder.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* 多租户上下文存储器, 多租户应用必须实现 {@link TenantContextHolder} 接口
* @author YongWu zheng
* @version V2.0 Created by 2020.12.1 13:31
*/
@Component
public clreplaced UmsTenantContextHolder implements TenantContextHolder {
/**
* 租户 ID 缓存的时间, 单位秒
*/
public static final int TIMEOUT = 30;
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private StringRedisTemplate stringRedisTemplate;
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Autowired
private Auth2Properties auth2Properties;
@Override
@NonNull
public String tenantIdHandle(@NonNull HttpServletRequest request, @Nullable String tenantId) throws TenantIdNotFoundException {
final String sessionId = request.getSession().getId();
try {
if (tenantId == null) {
/* 从 request 中解析, 比如通过特定的请求头/cookie/requestURI解析;
* 示例中, 我们约定请求中的 uri 最后的路径值即为 tenantId, 比如 /user/signUp/111111 -> tenantId = 111111,
* /user/mobile/111111 -> tenantId = 111111
* 如果是第三方登录: /auth2/authorization/110110/gitee -> tenantId = 110110
*/
String uri = request.getServletPath();
String auth2RedirectUrlPrefix = auth2Properties.getAuthLoginUrlPrefix();
// noinspection AlibabaUndefineMagicConstant
if (auth2RedirectUrlPrefix.endsWith("/*")) {
auth2RedirectUrlPrefix = auth2RedirectUrlPrefix.substring(0, auth2RedirectUrlPrefix.length() - 2);
}
if (uri.startsWith(auth2RedirectUrlPrefix)) {
// 第三方登录获取 tenantId
final int endIndex = uri.lastIndexOf("/");
uri = uri.substring(0, endIndex);
}
tenantId = uri.substring(uri.lastIndexOf("/") + 1);
}
// 示例直接用 redis 作为缓存 tenantId, 当然 tenantId 也可以存储在 session
this.stringRedisTemplate.opsForValue().set(sessionId, tenantId, TIMEOUT, TimeUnit.SECONDS);
return tenantId;
} catch (Exception e) {
throw new TenantIdNotFoundException(ErrorCodeEnum.TENANT_ID_NOT_FOUND, null, sessionId);
}
}
@Override
@NonNull
public String getTenantId() throws TenantIdNotFoundException {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken)) {
// 已登录用户获取租户 id
return getTenantId(authentication);
}
// 未登录用户获取租户 id
String sessionId = null;
try {
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
sessionId = requestAttributes.getSessionId();
String tenantId = this.stringRedisTemplate.opsForValue().get(sessionId);
if (tenantId == null) {
throw new TenantIdNotFoundException(ErrorCodeEnum.TENANT_ID_NOT_FOUND, null, sessionId);
}
return tenantId;
} catch (Exception e) {
throw new TenantIdNotFoundException(ErrorCodeEnum.TENANT_ID_NOT_FOUND, null, sessionId);
}
}
}
19
Source : DeserializerTestController.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* 演示 redis 添加反序列化配置.<br>
* 目前添加了一些 Authentication 与 UserDetails 子类的反序列化器, 以解决 redis 缓存不能反序列化此类型的问题.<br>
* 具体配置 redis 反序列器的配置请看 {@link RedisCacheAutoConfiguration}{@code .getJackson2JsonRedisSerializer()} 方法.
* 注意: {@link UmsUserDetailsService} 的注册用户方法返回的
* {@link UserDetails} 的默认实现 {@link User} 已实现反序列化器, 如果是开发者自定义的子类, 需开发者自己实现反序列化器.
* @author YongWu zheng
* @version V2.0 Created by 2020/10/26 13:08
*/
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Controller
public clreplaced DeserializerTestController {
private final Logger log = LoggerFactory.getLogger(this.getClreplaced());
@Autowired
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/user/me")
@ResponseBody
public Map<String, Object> getCurrentUser(@AuthenticationPrincipal UserDetails userDetails, @SuppressWarnings("unused") HttpServletRequest request) throws JsonProcessingException {
Map<String, Object> map = new HashMap<>(2);
map.put("securityContextHolder", SecurityContextHolder.getContext().getAuthentication());
map.put("userDetails", userDetails);
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
log.info(JsonUtil.toJsonString(userDetails));
// start: redis 添加反序列化配置.
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// Auth2Jackson2Module 为此项目实现的反序列化配置
mapper.registerModules(new CoreJackson2Module(), new WebJackson2Module(), new Auth2Jackson2Module());
// end: redis 添加反序列化配置.
// 测试 redis 序列化 与 反序列化
if (authentication instanceof UsernamePreplacedwordAuthenticationToken) {
UsernamePreplacedwordAuthenticationToken auth2AuthenticationToken = (UsernamePreplacedwordAuthenticationToken) authentication;
stringRedisTemplate.opsForValue().set("testJsonDeserializer", mapper.writeValuereplacedtring(auth2AuthenticationToken));
final String testJsonDeserializer = stringRedisTemplate.opsForValue().get("testJsonDeserializer");
final UsernamePreplacedwordAuthenticationToken token = mapper.readValue(testJsonDeserializer, UsernamePreplacedwordAuthenticationToken.clreplaced);
log.info("testJsonDeserializer: {}", token);
}
if (authentication instanceof SmsCodeLoginAuthenticationToken) {
SmsCodeLoginAuthenticationToken aToken = (SmsCodeLoginAuthenticationToken) authentication;
stringRedisTemplate.opsForValue().set("testJsonDeserializer", mapper.writeValuereplacedtring(aToken));
final String testJsonDeserializer = stringRedisTemplate.opsForValue().get("testJsonDeserializer");
final SmsCodeLoginAuthenticationToken token = mapper.readValue(testJsonDeserializer, SmsCodeLoginAuthenticationToken.clreplaced);
log.info("testJsonDeserializer: {}", token);
}
return map;
}
}
19
Source : DeserializerTestController.java
with MIT License
from ZeroOrInfinity
with MIT License
from ZeroOrInfinity
/**
* 演示 redis 添加反序列化配置.<br>
* 目前添加了一些 Authentication 与 UserDetails 子类的反序列化器, 以解决 redis 缓存不能反序列化此类型的问题.<br>
* 具体配置 redis 反序列器的配置请看 {@link RedisCacheAutoConfiguration}{@code .getJackson2JsonRedisSerializer()} 方法.
* 注意: {@link UmsUserDetailsService} 的注册用户方法返回的
* {@link UserDetails} 的默认实现 {@link User} 已实现反序列化器, 如果是开发者自定义的子类, 需开发者自己实现反序列化器.
* @author YongWu zheng
* @version V2.0 Created by 2020/10/26 13:08
*/
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@Controller
public clreplaced DeserializerTestController {
private final Logger log = LoggerFactory.getLogger(this.getClreplaced());
@Autowired
private StringRedisTemplate stringRedisTemplate;
@GetMapping("/user/me")
@ResponseBody
public Map<String, Object> getCurrentUser(@AuthenticationPrincipal UserDetails userDetails, @SuppressWarnings("unused") HttpServletRequest request) throws JsonProcessingException {
Map<String, Object> map = new HashMap<>(2);
map.put("securityContextHolder", SecurityContextHolder.getContext().getAuthentication());
map.put("userDetails", userDetails);
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
log.info(JsonUtil.toJsonString(userDetails));
// redis 添加反序列化配置.
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModules(new CoreJackson2Module(), new WebJackson2Module(), new JavaTimeModule(), new WebServerJackson2Module(), new OAuth2ClientJackson2Module(), new Auth2Jackson2Module());
// 测试 redis 序列化 与 反序列化
// jwt
{
Map<String, Object> headers = new LinkedHashMap<>();
headers.put("alg", "HS512");
Map<String, Object> claims = new LinkedHashMap<>();
claims.put("jti", UuidUtils.getUUID());
Jwt jwt = new Jwt("xxxx.xxxx.xxx", Instant.now(), Instant.now().plusSeconds(5000), headers, claims);
stringRedisTemplate.opsForValue().set("testJsonDeserializer", mapper.writeValuereplacedtring(jwt));
String testJsonDeserializer = stringRedisTemplate.opsForValue().get("testJsonDeserializer");
Jwt jwtDes = mapper.readValue(testJsonDeserializer, Jwt.clreplaced);
log.info("testJsonDeserializer: {}", jwtDes);
}
// JwtAuthenticationToken
{
Map<String, Object> headers = new LinkedHashMap<>();
headers.put("alg", "HS512");
Map<String, Object> claims = new LinkedHashMap<>();
claims.put("jti", UuidUtils.getUUID());
claims.put("scp", "write read");
Jwt jwt = new Jwt("xxxx.xxxx.xxx", Instant.now(), Instant.now().plusSeconds(5000), headers, claims);
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
JwtAuthenticationToken jwtToken = new JwtAuthenticationToken(jwt, authorities, "jwtToken");
stringRedisTemplate.opsForValue().set("testJsonDeserializer", mapper.writeValuereplacedtring(jwtToken));
String testJsonDeserializer = stringRedisTemplate.opsForValue().get("testJsonDeserializer");
JwtAuthenticationToken jwtTokenDes = mapper.readValue(testJsonDeserializer, JwtAuthenticationToken.clreplaced);
log.info("testJsonDeserializer: {}", jwtTokenDes);
}
// BearerTokenAuthentication
{
Map<String, Object> claims = new LinkedHashMap<>();
claims.put("jti", UuidUtils.getUUID());
Set<String> scopes = new LinkedHashSet<>();
scopes.add("write");
scopes.add("read");
List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList();
DefaultOAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal("test", claims, authorities);
OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "xxxx.xxxx.xxxx2", Instant.now(), Instant.now().plusSeconds(5000), scopes);
BearerTokenAuthentication bearerToken = new BearerTokenAuthentication(principal, accessToken, authorities);
stringRedisTemplate.opsForValue().set("testJsonDeserializer", mapper.writeValuereplacedtring(bearerToken));
String testJsonDeserializer = stringRedisTemplate.opsForValue().get("testJsonDeserializer");
BearerTokenAuthentication bearerTokenDes = mapper.readValue(testJsonDeserializer, BearerTokenAuthentication.clreplaced);
log.info("testJsonDeserializer: {}", bearerTokenDes);
}
if (authentication instanceof UsernamePreplacedwordAuthenticationToken) {
UsernamePreplacedwordAuthenticationToken authenticationToken = (UsernamePreplacedwordAuthenticationToken) authentication;
stringRedisTemplate.opsForValue().set("testJsonDeserializer", mapper.writeValuereplacedtring(authenticationToken));
final String testJsonDeserializer = stringRedisTemplate.opsForValue().get("testJsonDeserializer");
final UsernamePreplacedwordAuthenticationToken token = mapper.readValue(testJsonDeserializer, UsernamePreplacedwordAuthenticationToken.clreplaced);
log.info("testJsonDeserializer: {}", token);
}
if (authentication instanceof SmsCodeLoginAuthenticationToken) {
SmsCodeLoginAuthenticationToken aToken = (SmsCodeLoginAuthenticationToken) authentication;
stringRedisTemplate.opsForValue().set("testJsonDeserializer", mapper.writeValuereplacedtring(aToken));
final String testJsonDeserializer = stringRedisTemplate.opsForValue().get("testJsonDeserializer");
final SmsCodeLoginAuthenticationToken token = mapper.readValue(testJsonDeserializer, SmsCodeLoginAuthenticationToken.clreplaced);
log.info("testJsonDeserializer: {}", token);
}
if (authentication instanceof RememberMeAuthenticationToken) {
RememberMeAuthenticationToken aToken = (RememberMeAuthenticationToken) authentication;
stringRedisTemplate.opsForValue().set("testJsonDeserializer", mapper.writeValuereplacedtring(aToken));
final String testJsonDeserializer = stringRedisTemplate.opsForValue().get("testJsonDeserializer");
final RememberMeAuthenticationToken token = mapper.readValue(testJsonDeserializer, RememberMeAuthenticationToken.clreplaced);
log.info("testJsonDeserializer: {}", token);
}
return map;
}
}
19
Source : LogController.java
with Apache License 2.0
from Zephery
with Apache License 2.0
from Zephery
/**
* Created by Zephery on 2017/6/23.
*/
@Slf4j
@Controller
public clreplaced LogController {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private MetricsEndpoint metricsEndpoint;
@Resource
private Environment environment;
private static final String METRIC_NAME = "system.cpu.usage";
@RequestMapping("/log")
public ModelAndView log(HttpServletRequest request) throws IOException {
log.info("log");
String temp = stringRedisTemplate.opsForValue().get("daterange");
String pv_count = stringRedisTemplate.opsForValue().get("pv_count");
String visitor_count = stringRedisTemplate.opsForValue().get("visitor_count");
String bounce_ratio = stringRedisTemplate.opsForValue().get("bounce_ratio");
String avg_visit_time = stringRedisTemplate.opsForValue().get("avg_visit_time");
String top_ten = stringRedisTemplate.opsForValue().get("top_ten");
String source = stringRedisTemplate.opsForValue().get("source");
String rukou_str = stringRedisTemplate.opsForValue().get("rukouyemian");
String diyu_str = stringRedisTemplate.opsForValue().get("diyu");
String pv_sum = stringRedisTemplate.opsForValue().get("pv_sum");
String uv_sum = stringRedisTemplate.opsForValue().get("uv_sum");
Gson gson = new Gson();
// 前十访问页面
JsonArray array = JsonParser.parseString(top_ten).getAsJsonArray();
List<TopTen> topTens = new ArrayList<>();
for (JsonElement element : array) {
TopTen topTen = gson.fromJson(element, TopTen.clreplaced);
topTens.add(topTen);
}
log.info("前十访问页面");
// 来源统计
JsonArray sourcearray = JsonParser.parseString(source).getAsJsonArray();
List<FanPie> sourcelist = new ArrayList<>();
for (JsonElement element : sourcearray) {
FanPie fanPie = gson.fromJson(element, FanPie.clreplaced);
sourcelist.add(fanPie);
}
log.info("来源统计");
// 前十入口页面
JsonArray rukouarray = JsonParser.parseString(rukou_str).getAsJsonArray();
List<TopTen> rukou = new ArrayList<>();
for (JsonElement element : rukouarray) {
TopTen topTen = gson.fromJson(element, TopTen.clreplaced);
rukou.add(topTen);
}
log.info("前十入口页面");
// 地域地图
JsonArray diyuarray = JsonParser.parseString(diyu_str).getAsJsonArray();
List<TopTen> diyu = new ArrayList<>();
for (JsonElement element : diyuarray) {
TopTen topTen = gson.fromJson(element, TopTen.clreplaced);
diyu.add(topTen);
}
rukou.sort((o1, o2) -> {
if (o1.getPv_count() > o2.getPv_count()) {
return -1;
} else {
return 1;
}
});
diyu.sort((o1, o2) -> {
if (o1.getPv_count() > o2.getPv_count()) {
return -1;
} else {
return 1;
}
});
List<String> jmx_memory_use = new ArrayList<>();
Integer used = metricsEndpoint.metric("jvm.memory.used", null).getMeasurements().stream().filter(Objects::nonNull).findFirst().map(MetricsEndpoint.Sample::getValue).filter(Double::isFinite).orElse(0.0D).intValue() / (1024 * 1024);
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
jmx_memory_use.add(used.toString());
List<String> cpu_usage = new ArrayList<>();
Integer jmx_memory_committed = metricsEndpoint.metric("jvm.memory.committed", null).getMeasurements().stream().filter(Objects::nonNull).findFirst().map(MetricsEndpoint.Sample::getValue).filter(Double::isFinite).orElse(0.0D).intValue() / (1024 * 1024);
JsonArray memoryPoolJson = JMXClient.getInstance().getMemoryPoolDetail();
ModelAndView mv = new ModelAndView();
String ip = IPUtils.getIpAddr(request);
// String yourcity = IPUtils.getAddressByIP(ip);
String yourcity = "功能已注释";
log.info("yourcity is {}", yourcity);
mv.addObject("ip", ip);
mv.addObject("yourcity", yourcity);
mv.addObject("daterange", JsonParser.parseString(temp).getAsJsonArray());
mv.addObject("topTens", topTens);
mv.addObject("pv_count", pv_count);
mv.addObject("visitor_count", visitor_count);
mv.addObject("bounce_ratio", bounce_ratio);
mv.addObject("sourcelist", sourcelist);
mv.addObject("rukou", rukou.subList(0, rukou.size() > 5 ? 5 : rukou.size()));
mv.addObject("avg_visit_time", avg_visit_time);
mv.addObject("diyu", diyu);
mv.addObject("diyumax", diyu.get(0).getPv_count());
mv.addObject("pv_sum", pv_sum);
mv.addObject("uv_sum", uv_sum);
mv.addObject("jmx_memory_use", jmx_memory_use);
cpu_usage.add("0.2");
cpu_usage.add("0.2");
cpu_usage.add("0.3");
mv.addObject("cpu_usage", cpu_usage);
mv.addObject("jmx_memory_committed", jmx_memory_committed);
mv.addObject("memoryPoolJson", memoryPoolJson);
log.info("host");
// host
Set<String> profiles = new HashSet<>(Arrays.asList(environment.getActiveProfiles()));
if (profiles.contains("dev")) {
mv.addObject("host", "localhost");
} else {
mv.addObject("host", IPUtils.getServerIp());
}
mv.setViewName("log");
return mv;
}
@RequestMapping("/jmx")
@ResponseBody
public void jmx(HttpServletResponse response) throws IOException {
Double jvmMemUsed = metricsEndpoint.metric("jvm.memory.used", null).getMeasurements().stream().filter(Objects::nonNull).findFirst().map(MetricsEndpoint.Sample::getValue).filter(Double::isFinite).orElse(0.0D);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
log.info("jvmMemUsed is {}", jvmMemUsed.intValue());
response.getWriter().write(String.valueOf(jvmMemUsed.intValue() / (1024 * 1024)));
}
@RequestMapping("/cpu")
@ResponseBody
public void cpu(HttpServletResponse response) throws IOException {
String aa = JMXClient.getInstance().getCpuUsage();
Double systemCpuUsage = metricsEndpoint.metric(METRIC_NAME, null).getMeasurements().stream().filter(Objects::nonNull).findFirst().map(MetricsEndpoint.Sample::getValue).filter(Double::isFinite).orElse(0.0D);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(systemCpuUsage.toString());
}
}
19
Source : CYController.java
with Apache License 2.0
from Zephery
with Apache License 2.0
from Zephery
/**
* @author Zephery
* @since 2018/1/30 18:51
*/
@Slf4j
@Controller
@RequestMapping("/cy")
public clreplaced CYController {
@Resource
private StringRedisTemplate stringRedisTemplate;
// 该接口只有当畅言已登录,getUserInfo返回未登录时,才会被调用用来登录自身网站
@RequestMapping("/login")
public void loginByCy(@RequestParam(value = "callback") String callback, @RequestParam(value = "user_id") String user_id, @RequestParam(value = "nickname") String nickname, @RequestParam(value = "sign") String sign, @RequestParam(value = "img_url") String img_url, @RequestParam(value = "profile_url") String profile_url, HttpServletResponse resp) throws Exception {
// 自己网站的登录逻辑,记录登录信息到cookie
Cookie cookie = new Cookie("user_id", user_id);
resp.addCookie(cookie);
resp.getWriter().write(callback + "({\"user_id\":" + user_id + ",reload_page:0})");
}
@RequestMapping("/loginout")
public void loginBySite(@RequestParam(value = "callback") String callback, HttpServletResponse resp) throws Exception {
// 清除自己网站cookies信息,同时前端logout.js代码用来清理畅言cookie
resp.getWriter().write(callback + "({\"code\":\"1\",reload_page:0, js-src:logout.js})");
}
// 该接口在页面每一次加载时都会被调用,用来判断用户在自己网站是否登录
@RequestMapping("/getUserInfo")
@SuppressWarnings("unchecked")
public void getUserInfo(@RequestParam(value = "callback") String callback, HttpServletRequest res, HttpServletResponse resp) throws Exception {
UserInfo userinfo = new UserInfo();
Cookie[] cookies = res.getCookies();
if (!isContains("user_id", cookies)) {
// 此处为模拟逻辑,具体实现可以变化
// 用户未登录
userinfo.setIs_login(0);
} else {
// 用户已登录
userinfo.setIs_login(1);
User user = new User();
// user.setUser_id(Integer.parseInt(getCookieValue("user_id", cookies))); //该值具体根据自己用户系统设定
// user.setNickname(getCookieValue("nickname", cookies)); //该值具体根据自己用户系统设定
// user.setImg_url(getCookieValue("img_url", cookies)); //该值具体根据自己用户系统设定,可以为空
// user.setProfile_url(getCookieValue("profile_url", cookies));//该值具体根据自己用户系统设定,可以为空
// user.setSign(getCookieValue("sign", cookies)); //签名已弃用,任意赋值即可
// userinfo.setUser(user);
new Thread(() -> stringRedisTemplate.opsForList().leftPush("cyuser", user.toString()));
}
// resp.setContentType("application/x-javascript");//指定传输格式为js
// resp.getWriter().write(callback + "(" + JSONArray.toJSONString(userinfo) + ")");//拼接成jsonp格式
}
// 该方法判断cookie中是否存在键值为key的value值
public boolean isContains(String key, Cookie[] cookies) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(key)) {
if (cookie.getValue() != null) {
return true;
} else {
return false;
}
}
}
return false;
}
// 该方法获取cookie中键值为key的value值
public Object getCookieValue(String key, Cookie[] cookies) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(key))
return cookie.getValue();
}
return null;
}
}
19
Source : RedisServiceImpl.java
with Apache License 2.0
from zdRan
with Apache License 2.0
from zdRan
/**
* Create by ranzd on 2018/9/11
*
* @author [email protected]
*/
@Service
public clreplaced RedisServiceImpl implements RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private Logger logger = LoggerFactory.getLogger(RedisServiceImpl.clreplaced);
@Override
public void setStr(String key, String value) {
logger.info("插入 Redis 数据。入参:key:{},value:{}", key, value);
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
operations.set(key, value);
}
@Override
public String getStr(String key) {
logger.info("获取 Redis 数据。入参:key:{}", key);
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
String value = operations.get(key);
logger.info("获取 Redis 数据。出参:value:{}", value);
return value;
}
@Override
public void delStr(String key) {
logger.info("删除 Redis 数据。入参:key:{}", key);
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
operations.getOperations().delete(key);
}
}
19
Source : RedisUtil.java
with Apache License 2.0
from ZainZhao
with Apache License 2.0
from ZainZhao
/**
* redis操作Service的实现类
*/
@Service
public clreplaced RedisUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
public void setStr(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
public String getStr(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 设置超期时间
*/
public boolean expireStr(String key, long expire) {
return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
public void removeStr(String key) {
stringRedisTemplate.delete(key);
}
public void removeObj(String key) {
redisTemplate.delete(key);
}
public void setObj(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getObj(String key) {
return redisTemplate.opsForValue().get(key);
}
}
19
Source : RedisUtil.java
with Apache License 2.0
from ZainZhao
with Apache License 2.0
from ZainZhao
/**
* redis操作Service的实现类
*/
@Service
public clreplaced RedisUtil {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
public void setStr(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
public String getStr(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 设置超期时间
*/
public boolean expireStr(String key, long expire) {
return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
public void removeStr(String key) {
stringRedisTemplate.delete(key);
}
public void removeObj(String key) {
redisTemplate.delete(key);
}
public void setObj(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object getObj(String key) {
return redisTemplate.opsForValue().get(key);
}
}
19
Source : RedisServiceImpl.java
with MIT License
from yzsunlei
with MIT License
from yzsunlei
/**
* redis操作Service的实现类
* Created by macro on 2018/8/7.
*/
@Service
public clreplaced RedisServiceImpl implements RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
@Override
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@Override
public boolean expire(String key, long expire) {
return stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
@Override
public void remove(String key) {
stringRedisTemplate.delete(key);
}
@Override
public Long increment(String key, long delta) {
return stringRedisTemplate.opsForValue().increment(key, delta);
}
}
19
Source : SysRoleProducer.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* Role 角色相关消息的 Producer
*/
@Component
public clreplaced SysRoleProducer {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 发送 {@link SysRoleRefreshMessage} 消息
*/
public void sendRoleRefreshMessage() {
SysRoleRefreshMessage message = new SysRoleRefreshMessage();
RedisMessageUtils.sendChannelMessage(stringRedisTemplate, message);
}
}
19
Source : SysPermissionProducer.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* Permission 权限相关消息的 Producer
*/
@Component
public clreplaced SysPermissionProducer {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 发送 {@link SysRoleMenuRefreshMessage} 消息
*/
public void sendRoleMenuRefreshMessage() {
SysRoleMenuRefreshMessage message = new SysRoleMenuRefreshMessage();
RedisMessageUtils.sendChannelMessage(stringRedisTemplate, message);
}
}
19
Source : SysMenuProducer.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* Menu 菜单相关消息的 Producer
*/
@Component
public clreplaced SysMenuProducer {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 发送 {@link SysMenuRefreshMessage} 消息
*/
public void sendMenuRefreshMessage() {
SysMenuRefreshMessage message = new SysMenuRefreshMessage();
RedisMessageUtils.sendChannelMessage(stringRedisTemplate, message);
}
}
19
Source : SysDictDataProducer.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* DictData 字典数据相关消息的 Producer
*/
@Component
public clreplaced SysDictDataProducer {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 发送 {@link SysDictDataRefreshMessage} 消息
*/
public void sendDictDataRefreshMessage() {
SysDictDataRefreshMessage message = new SysDictDataRefreshMessage();
RedisMessageUtils.sendChannelMessage(stringRedisTemplate, message);
}
}
19
Source : SysDeptProducer.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* Dept 部门相关消息的 Producer
*/
@Component
public clreplaced SysDeptProducer {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 发送 {@link SysDeptRefreshMessage} 消息
*/
public void sendDeptRefreshMessage() {
SysDeptRefreshMessage message = new SysDeptRefreshMessage();
RedisMessageUtils.sendChannelMessage(stringRedisTemplate, message);
}
}
19
Source : SysCaptchaRedisDAO.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* 验证码的 Redis DAO
*
* @author 芋道源码
*/
@Repository
public clreplaced SysCaptchaRedisDAO {
@Resource
private StringRedisTemplate stringRedisTemplate;
public String get(String uuid) {
String redisKey = formatKey(uuid);
return stringRedisTemplate.opsForValue().get(redisKey);
}
public void set(String uuid, String code, Duration timeout) {
String redisKey = formatKey(uuid);
stringRedisTemplate.opsForValue().set(redisKey, code, timeout);
}
public void delete(String uuid) {
String redisKey = formatKey(uuid);
stringRedisTemplate.delete(redisKey);
}
private static String formatKey(String uuid) {
return String.format(CAPTCHA_CODE.getKeyTemplate(), uuid);
}
}
19
Source : SysLoginUserRedisDAO.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* {@link LoginUser} 的 RedisDAO
*
* @author 芋道源码
*/
@Repository
public clreplaced SysLoginUserRedisDAO {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private SysUserSessionService sysUserSessionService;
public LoginUser get(String sessionId) {
String redisKey = formatKey(sessionId);
return JsonUtils.parseObject(stringRedisTemplate.opsForValue().get(redisKey), LoginUser.clreplaced);
}
public void set(String sessionId, LoginUser loginUser) {
String redisKey = formatKey(sessionId);
stringRedisTemplate.opsForValue().set(redisKey, JsonUtils.toJsonString(loginUser), Duration.ofMillis(sysUserSessionService.getSessionTimeoutMillis()));
}
public void delete(String sessionId) {
String redisKey = formatKey(sessionId);
stringRedisTemplate.delete(redisKey);
}
private static String formatKey(String sessionId) {
return String.format(LOGIN_USER.getKeyTemplate(), sessionId);
}
}
19
Source : InfConfigProducer.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* Config 配置相关消息的 Producer
*/
@Component
public clreplaced InfConfigProducer {
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 发送 {@link InfConfigRefreshMessage} 消息
*/
public void sendConfigRefreshMessage() {
InfConfigRefreshMessage message = new InfConfigRefreshMessage();
RedisMessageUtils.sendChannelMessage(stringRedisTemplate, message);
}
}
19
Source : IdempotentRedisDAO.java
with MIT License
from YunaiV
with MIT License
from YunaiV
/**
* 幂等 Redis DAO
*
* @author 芋道源码
*/
@AllArgsConstructor
public clreplaced IdempotentRedisDAO {
private static final RedisKeyDefine IDEMPOTENT = new RedisKeyDefine("幂等操作", // 参数为 uuid
"idempotent:%s", STRING, String.clreplaced, RedisKeyDefine.TimeoutTypeEnum.DYNAMIC);
private final StringRedisTemplate redisTemplate;
public Boolean setIfAbsent(String key, long timeout, TimeUnit timeUnit) {
String redisKey = formatKey(key);
return redisTemplate.opsForValue().setIfAbsent(redisKey, "", timeout, timeUnit);
}
private static String formatKey(String key) {
return String.format(IDEMPOTENT.getKeyTemplate(), key);
}
}
19
Source : IdempotentConfiguration.java
with MIT License
from YunaiV
with MIT License
from YunaiV
@Bean
public IdempotentRedisDAO idempotentRedisDAO(StringRedisTemplate stringRedisTemplate) {
return new IdempotentRedisDAO(stringRedisTemplate);
}
See More Examples