| | |
| | | import org.springframework.stereotype.Service; |
| | | |
| | | import javax.annotation.Resource; |
| | | import java.util.*; |
| | | import java.util.concurrent.ConcurrentHashMap; |
| | | import java.util.stream.Collectors; |
| | | |
| | | @Service("userService") |
| | | public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { |
| | | |
| | | /** 批量查询缓存:key = 排序后的 ids 拼接,value = (过期时间戳, 用户列表),TTL 5 分钟 */ |
| | | private static final long CACHE_TTL_MS = 5 * 60 * 1000L; |
| | | private static final ConcurrentHashMap<String, CacheEntry<List<User>>> USER_MANY_CACHE = new ConcurrentHashMap<>(64); |
| | | |
| | | @Resource |
| | | private UserRoleService userRoleService; |
| | |
| | | if (Cools.isEmpty(username)) { |
| | | return null; |
| | | } |
| | | User user = baseMapper.selectByUsername(username, tenantId); |
| | | if (user != null) { |
| | | user.setRoles(userRoleService.listByUserId(user.getId())); |
| | | user.setAuthorities(roleMenuService.listMenuByUserId(user.getId(), null)); |
| | | } |
| | | return user; |
| | | return baseMapper.selectByUsernameWithoutTenant(username, tenantId); |
| | | } |
| | | |
| | | @Override |
| | | public User getByIdRel(Long userId) { |
| | | User user = this.getById(userId); |
| | | public User getByEmail(String email, Long tenantId) { |
| | | if (Cools.isEmpty(email)) { |
| | | return null; |
| | | } |
| | | return baseMapper.selectByEmailWithoutTenant(email, tenantId); |
| | | } |
| | | |
| | | @Override |
| | | public User setUserAuthInfo(User user) { |
| | | if (user != null) { |
| | | user.setRoles(userRoleService.listByUserId(user.getId())); |
| | | user.setAuthorities(roleMenuService.listMenuByUserId(user.getId(), null)); |
| | |
| | | return password == null ? null : bCryptPasswordEncoder.encode(password); |
| | | } |
| | | |
| | | @Override |
| | | public User selectByUsernameWithoutTenant(String username, Long tenantId) { |
| | | return baseMapper.selectByUsernameWithoutTenant(username,tenantId); |
| | | } |
| | | |
| | | @Override |
| | | public List<User> listByIdsCached(Collection<Long> ids) { |
| | | if (ids == null || ids.isEmpty()) { |
| | | return Collections.emptyList(); |
| | | } |
| | | String key = ids.stream().sorted().map(Object::toString).collect(Collectors.joining(",")); |
| | | long now = System.currentTimeMillis(); |
| | | CacheEntry<List<User>> entry = USER_MANY_CACHE.get(key); |
| | | if (entry != null && entry.expireAt > now) { |
| | | return entry.data; |
| | | } |
| | | List<User> list = listByIds(ids); |
| | | USER_MANY_CACHE.put(key, new CacheEntry<>(now + CACHE_TTL_MS, list)); |
| | | return list; |
| | | } |
| | | |
| | | private static class CacheEntry<T> { |
| | | final long expireAt; |
| | | final T data; |
| | | CacheEntry(long expireAt, T data) { |
| | | this.expireAt = expireAt; |
| | | this.data = data; |
| | | } |
| | | } |
| | | |
| | | } |