Commit cf1e17c7 authored by dbdu's avatar dbdu
Browse files

Merge branch 'master' of https://gitee.com/elunez/eladmin

parents 425f910f 3379f4a9
......@@ -27,10 +27,7 @@ import me.zhengjie.modules.system.service.dto.RoleDto;
import me.zhengjie.modules.system.service.dto.RoleQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.ThrowableUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
......
......@@ -15,8 +15,10 @@
*/
package me.zhengjie.modules.system.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.service.UserCacheClean;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.exception.EntityExistException;
......@@ -40,6 +42,7 @@ import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
......@@ -59,6 +62,7 @@ public class RoleServiceImpl implements RoleService {
private final RoleSmallMapper roleSmallMapper;
private final RedisUtils redisUtils;
private final UserRepository userRepository;
private final UserCacheClean userCacheClean;
@Override
public List<RoleDto> queryAll() {
......@@ -68,12 +72,12 @@ public class RoleServiceImpl implements RoleService {
@Override
public List<RoleDto> queryAll(RoleQueryCriteria criteria) {
return roleMapper.toDto(roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
return roleMapper.toDto(roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
}
@Override
public Object queryAll(RoleQueryCriteria criteria, Pageable pageable) {
Page<Role> page = roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
Page<Role> page = roleRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
return PageUtil.toPage(page.map(roleMapper::toDto));
}
......@@ -82,15 +86,15 @@ public class RoleServiceImpl implements RoleService {
@Transactional(rollbackFor = Exception.class)
public RoleDto findById(long id) {
Role role = roleRepository.findById(id).orElseGet(Role::new);
ValidationUtil.isNull(role.getId(),"Role","id",id);
ValidationUtil.isNull(role.getId(), "Role", "id", id);
return roleMapper.toDto(role);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(Role resources) {
if(roleRepository.findByName(resources.getName()) != null){
throw new EntityExistException(Role.class,"username",resources.getName());
if (roleRepository.findByName(resources.getName()) != null) {
throw new EntityExistException(Role.class, "username", resources.getName());
}
roleRepository.save(resources);
}
......@@ -99,12 +103,12 @@ public class RoleServiceImpl implements RoleService {
@Transactional(rollbackFor = Exception.class)
public void update(Role resources) {
Role role = roleRepository.findById(resources.getId()).orElseGet(Role::new);
ValidationUtil.isNull(role.getId(),"Role","id",resources.getId());
ValidationUtil.isNull(role.getId(), "Role", "id", resources.getId());
Role role1 = roleRepository.findByName(resources.getName());
if(role1 != null && !role1.getId().equals(role.getId())){
throw new EntityExistException(Role.class,"username",resources.getName());
if (role1 != null && !role1.getId().equals(role.getId())) {
throw new EntityExistException(Role.class, "username", resources.getName());
}
role.setName(resources.getName());
role.setDescription(resources.getDescription());
......@@ -113,20 +117,16 @@ public class RoleServiceImpl implements RoleService {
role.setLevel(resources.getLevel());
roleRepository.save(role);
// 更新相关缓存
delCaches(role.getId());
delCaches(role.getId(), null);
}
@Override
public void updateMenu(Role resources, RoleDto roleDTO) {
Role role = roleMapper.toEntity(roleDTO);
List<User> users = userRepository.findByRoleId(role.getId());
Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet());
// 更新菜单
role.setMenus(resources.getMenus());
// 清理缓存
redisUtils.delByKeys("menu::user:",userIds);
redisUtils.delByKeys("role::auth:",userIds);
redisUtils.del("role::id:" + resources.getId());
delCaches(resources.getId(), users);
roleRepository.save(role);
}
......@@ -142,7 +142,7 @@ public class RoleServiceImpl implements RoleService {
public void delete(Set<Long> ids) {
for (Long id : ids) {
// 更新相关缓存
delCaches(id);
delCaches(id, null);
}
roleRepository.deleteAllByIdIn(ids);
}
......@@ -166,7 +166,7 @@ public class RoleServiceImpl implements RoleService {
public List<GrantedAuthority> mapToGrantedAuthorities(UserDto user) {
Set<String> permissions = new HashSet<>();
// 如果是管理员直接返回
if(user.getIsAdmin()){
if (user.getIsAdmin()) {
permissions.add("admin");
return permissions.stream().map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
......@@ -183,7 +183,7 @@ public class RoleServiceImpl implements RoleService {
public void download(List<RoleDto> roles, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (RoleDto role : roles) {
Map<String,Object> map = new LinkedHashMap<>();
Map<String, Object> map = new LinkedHashMap<>();
map.put("角色名称", role.getName());
map.put("角色级别", role.getLevel());
map.put("描述", role.getDescription());
......@@ -193,21 +193,9 @@ public class RoleServiceImpl implements RoleService {
FileUtil.downloadExcel(list, response);
}
/**
* 清理缓存
* @param id /
*/
public void delCaches(Long id){
List<User> users = userRepository.findByRoleId(id);
Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet());
redisUtils.delByKeys("data::user:",userIds);
redisUtils.delByKeys("menu::user:",userIds);
redisUtils.delByKeys("role::auth:",userIds);
}
@Override
public void verification(Set<Long> ids) {
if(userRepository.countByRoles(ids) > 0){
if (userRepository.countByRoles(ids) > 0) {
throw new BadRequestException("所选角色存在用户关联,请解除关联再试!");
}
}
......@@ -216,4 +204,21 @@ public class RoleServiceImpl implements RoleService {
public List<Role> findInMenuId(List<Long> menuIds) {
return roleRepository.findInMenuId(menuIds);
}
/**
* 清理缓存
* @param id /
*/
public void delCaches(Long id, List<User> users) {
users = CollectionUtil.isEmpty(users) ? userRepository.findByRoleId(id) : users;
if (CollectionUtil.isNotEmpty(users)) {
users.forEach(item -> userCacheClean.cleanUserCache(item.getUsername()));
Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet());
redisUtils.delByKeys(CacheKey.DATE_USER, userIds);
redisUtils.delByKeys(CacheKey.MENU_USER, userIds);
redisUtils.delByKeys(CacheKey.ROLE_AUTH, userIds);
redisUtils.del(CacheKey.ROLE_ID + id);
}
}
}
......@@ -17,6 +17,7 @@ package me.zhengjie.modules.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.config.FileProperties;
import me.zhengjie.modules.security.service.UserCacheClean;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.exception.EntityNotFoundException;
......@@ -35,7 +36,9 @@ import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.File;
import java.io.IOException;
import java.util.*;
......@@ -54,16 +57,17 @@ public class UserServiceImpl implements UserService {
private final UserMapper userMapper;
private final FileProperties properties;
private final RedisUtils redisUtils;
private final UserCacheClean userCacheClean;
@Override
public Object queryAll(UserQueryCriteria criteria, Pageable pageable) {
Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
Page<User> page = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
return PageUtil.toPage(page.map(userMapper::toDto));
}
@Override
public List<UserDto> queryAll(UserQueryCriteria criteria) {
List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
List<User> users = userRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
return userMapper.toDto(users);
}
......@@ -72,18 +76,18 @@ public class UserServiceImpl implements UserService {
@Transactional(rollbackFor = Exception.class)
public UserDto findById(long id) {
User user = userRepository.findById(id).orElseGet(User::new);
ValidationUtil.isNull(user.getId(),"User","id",id);
ValidationUtil.isNull(user.getId(), "User", "id", id);
return userMapper.toDto(user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(User resources) {
if(userRepository.findByUsername(resources.getUsername())!=null){
throw new EntityExistException(User.class,"username",resources.getUsername());
if (userRepository.findByUsername(resources.getUsername()) != null) {
throw new EntityExistException(User.class, "username", resources.getUsername());
}
if(userRepository.findByEmail(resources.getEmail())!=null){
throw new EntityExistException(User.class,"email",resources.getEmail());
if (userRepository.findByEmail(resources.getEmail()) != null) {
throw new EntityExistException(User.class, "email", resources.getEmail());
}
userRepository.save(resources);
}
......@@ -92,22 +96,22 @@ public class UserServiceImpl implements UserService {
@Transactional(rollbackFor = Exception.class)
public void update(User resources) {
User user = userRepository.findById(resources.getId()).orElseGet(User::new);
ValidationUtil.isNull(user.getId(),"User","id",resources.getId());
ValidationUtil.isNull(user.getId(), "User", "id", resources.getId());
User user1 = userRepository.findByUsername(resources.getUsername());
User user2 = userRepository.findByEmail(resources.getEmail());
if(user1 !=null&&!user.getId().equals(user1.getId())){
throw new EntityExistException(User.class,"username",resources.getUsername());
if (user1 != null && !user.getId().equals(user1.getId())) {
throw new EntityExistException(User.class, "username", resources.getUsername());
}
if(user2!=null&&!user.getId().equals(user2.getId())){
throw new EntityExistException(User.class,"email",resources.getEmail());
if (user2 != null && !user.getId().equals(user2.getId())) {
throw new EntityExistException(User.class, "email", resources.getEmail());
}
// 如果用户的角色改变
if (!resources.getRoles().equals(user.getRoles())) {
redisUtils.del("data::user:" + resources.getId());
redisUtils.del("menu::user:" + resources.getId());
redisUtils.del("role::auth:" + resources.getId());
redisUtils.del(CacheKey.DATE_USER + resources.getId());
redisUtils.del(CacheKey.MENU_USER + resources.getId());
redisUtils.del(CacheKey.ROLE_AUTH + resources.getId());
}
// 如果用户名称修改
if(!resources.getUsername().equals(user.getUsername())){
......@@ -164,8 +168,9 @@ public class UserServiceImpl implements UserService {
@Override
@Transactional(rollbackFor = Exception.class)
public void updatePass(String username, String pass) {
userRepository.updatePass(username,pass,new Date());
userRepository.updatePass(username, pass, new Date());
redisUtils.del("user::username:" + username);
flushCache(username);
}
@Override
......@@ -177,18 +182,23 @@ public class UserServiceImpl implements UserService {
user.setAvatarPath(Objects.requireNonNull(file).getPath());
user.setAvatarName(file.getName());
userRepository.save(user);
if(StringUtils.isNotBlank(oldPath)){
if (StringUtils.isNotBlank(oldPath)) {
FileUtil.del(oldPath);
}
redisUtils.del("user::username:" + user.getUsername());
return new HashMap<String,String>(1){{put("avatar",file.getName());}};
@NotBlank String username = user.getUsername();
redisUtils.del(CacheKey.USER_NAME + username);
flushCache(username);
return new HashMap<String, String>(1) {{
put("avatar", file.getName());
}};
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateEmail(String username, String email) {
userRepository.updateEmail(username,email);
redisUtils.del("user::username:" + username);
userRepository.updateEmail(username, email);
redisUtils.del(CacheKey.USER_NAME + username);
flushCache(username);
}
@Override
......@@ -196,7 +206,7 @@ public class UserServiceImpl implements UserService {
List<Map<String, Object>> list = new ArrayList<>();
for (UserDto userDTO : queryAll) {
List<String> roles = userDTO.getRoles().stream().map(RoleSmallDto::getName).collect(Collectors.toList());
Map<String,Object> map = new LinkedHashMap<>();
Map<String, Object> map = new LinkedHashMap<>();
map.put("用户名", userDTO.getUsername());
map.put("角色", roles);
map.put("部门", userDTO.getDept().getName());
......@@ -213,10 +223,21 @@ public class UserServiceImpl implements UserService {
/**
* 清理缓存
*
* @param id /
*/
public void delCaches(Long id, String username){
redisUtils.del("user::id:" + id);
redisUtils.del("user::username:" + username);
public void delCaches(Long id, String username) {
redisUtils.del(CacheKey.USER_ID + id);
redisUtils.del(CacheKey.USER_NAME + username);
flushCache(username);
}
/**
* 清理 登陆时 用户缓存信息
*
* @param username /
*/
private void flushCache(String username) {
userCacheClean.cleanUserCache(username);
}
}
......@@ -46,6 +46,8 @@ spring:
# 登录相关配置
login:
# 登录缓存
cache-enable: true
# 是否限制单用户登录
single: false
# 验证码
......@@ -86,8 +88,8 @@ generator:
#是否开启 swagger-ui
swagger:
enabled: true
# IP 本地解析
# IP 本地解析
ip:
local-parsing: true
......
......@@ -48,6 +48,8 @@ spring:
# 登录相关配置
login:
# 登录缓存
cache-enable: true
# 是否限制单用户登录
single: false
# 验证码
......@@ -83,7 +85,7 @@ jwt:
# IP 本地解析
ip:
local-parsing: true
local-parsing: false
#是否允许生成代码,生产环境设置为false
generator:
......
......@@ -17,16 +17,11 @@
<#if betweens??>
<#list betweens as column>
<#if column.queryType = 'BetWeen'>
<el-date-picker
<date-range-picker
v-model="query.${column.changeColumnName}"
:default-time="['00:00:00','23:59:59']"
type="daterange"
range-separator=":"
size="small"
class="date-item"
value-format="yyyy-MM-dd HH:mm:ss"
start-placeholder="${column.changeColumnName}Start"
end-placeholder="${column.changeColumnName}End"
end-placeholder="${column.changeColumnName}Start"
class="date-item"
/>
</#if>
</#list>
......@@ -125,6 +120,7 @@ import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
const defaultForm = { <#if columns??><#list columns as column>${column.changeColumnName}: null<#if column_has_next>, </#if></#list></#if> }
export default {
name: '${className}',
......
package me.zhengjie;
import me.zhengjie.modules.security.service.UserDetailsServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class LoginCacheTest {
@Resource(name = "userDetailsService")
private UserDetailsServiceImpl userDetailsService;
@Test
public void testCache() {
long start1 = System.currentTimeMillis();
int size = 10000;
for (int i = 0; i < size; i++) {
userDetailsService.loadUserByUsername("admin");
}
long end1 = System.currentTimeMillis();
//关闭缓存
userDetailsService.setEnableCache(false);
long start2 = System.currentTimeMillis();
for (int i = 0; i < size; i++) {
userDetailsService.loadUserByUsername("admin");
}
long end2 = System.currentTimeMillis();
System.out.print("使用缓存:" + (end1 - start1) + "毫秒\n 不使用缓存:" + (end2 - start2) + "毫秒");
}
}
......@@ -38,20 +38,20 @@ import java.util.Optional;
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "alipay")
@CacheConfig(cacheNames = "aliPay")
public class AliPayServiceImpl implements AliPayService {
private final AliPayRepository alipayRepository;
@Override
@Cacheable(key = "'id:1'")
@Cacheable(key = "'config'")
public AlipayConfig find() {
Optional<AlipayConfig> alipayConfig = alipayRepository.findById(1L);
return alipayConfig.orElseGet(AlipayConfig::new);
}
@Override
@CachePut(key = "'id:1'")
@CachePut(key = "'config'")
@Transactional(rollbackFor = Exception.class)
public AlipayConfig config(AlipayConfig alipayConfig) {
alipayConfig.setId(1L);
......
......@@ -43,7 +43,7 @@ public class EmailServiceImpl implements EmailService {
private final EmailRepository emailRepository;
@Override
@CachePut(key = "'id:1'")
@CachePut(key = "'config'")
@Transactional(rollbackFor = Exception.class)
public EmailConfig config(EmailConfig emailConfig, EmailConfig old) throws Exception {
emailConfig.setId(1L);
......@@ -55,7 +55,7 @@ public class EmailServiceImpl implements EmailService {
}
@Override
@Cacheable(key = "'id:1'")
@Cacheable(key = "'config'")
public EmailConfig find() {
Optional<EmailConfig> emailConfig = emailRepository.findById(1L);
return emailConfig.orElseGet(EmailConfig::new);
......
......@@ -65,14 +65,14 @@ public class QiNiuServiceImpl implements QiNiuService {
private Long maxSize;
@Override
@Cacheable(key = "'id:1'")
@Cacheable(key = "'config'")
public QiniuConfig find() {
Optional<QiniuConfig> qiniuConfig = qiNiuConfigRepository.findById(1L);
return qiniuConfig.orElseGet(QiniuConfig::new);
}
@Override
@CachePut(key = "'id:1'")
@CachePut(key = "'config'")
@Transactional(rollbackFor = Exception.class)
public QiniuConfig config(QiniuConfig qiniuConfig) {
qiniuConfig.setId(1L);
......
......@@ -3,5 +3,5 @@ alter table code_gen_config CHANGE id config_id BIGINT(20) AUTO_INCREMENT COMMEN
-- code_gen_config end --
-- code_column_config 表改动 start --
alter table code_column_config CHANGE id config_idcolumn_id BIGINT(20) AUTO_INCREMENT COMMENT 'ID';
alter table code_column_config CHANGE id column_id BIGINT(20) AUTO_INCREMENT COMMENT 'ID';
-- code_column_config end --
\ No newline at end of file
......@@ -381,7 +381,7 @@ INSERT INTO `sys_menu` VALUES (15, 10, 0, 1, '富文本', 'Editor', 'components/
INSERT INTO `sys_menu` VALUES (16, 36, 2, 1, '图床管理', 'Pictures', 'tools/picture/index', 33, 'image', 'pictures', b'0', b'0', b'0', 'pictures:list', NULL, NULL, '2018-12-28 09:36:53', NULL);
INSERT INTO `sys_menu` VALUES (18, 36, 3, 1, '存储管理', 'Storage', 'tools/storage/index', 34, 'qiniu', 'storage', b'0', b'0', b'0', 'storage:list', NULL, NULL, '2018-12-31 11:12:15', NULL);
INSERT INTO `sys_menu` VALUES (19, 36, 0, 1, '支付宝工具', 'AliPay', 'tools/aliPay/index', 37, 'alipay', 'aliPay', b'0', b'0', b'0', NULL, NULL, NULL, '2018-12-31 14:52:38', NULL);
INSERT INTO `sys_menu` VALUES (21, NULL, 2, 0, '多级菜单', NULL, '', 900, 'menu', 'nested', b'0', b'0', b'1', NULL, NULL, NULL, '2019-01-04 16:22:03', NULL);
INSERT INTO `sys_menu` VALUES (21, NULL, 2, 0, '多级菜单', NULL, '', 900, 'menu', 'nested', b'0', b'0', b'0', NULL, NULL, NULL, '2019-01-04 16:22:03', NULL);
INSERT INTO `sys_menu` VALUES (22, 21, 2, 1, '二级菜单1', NULL, 'nested/menu1/index', 999, 'menu', 'menu1', b'0', b'0', b'0', NULL, NULL, NULL, '2019-01-04 16:23:29', NULL);
INSERT INTO `sys_menu` VALUES (23, 21, 0, 1, '二级菜单2', NULL, 'nested/menu2/index', 999, 'menu', 'menu2', b'0', b'0', b'0', NULL, NULL, NULL, '2019-01-04 16:23:57', NULL);
INSERT INTO `sys_menu` VALUES (24, 22, 0, 1, '三级菜单1', NULL, 'nested/menu1/menu1-1', 999, 'menu', 'menu1-1', b'0', b'0', b'0', NULL, NULL, NULL, '2019-01-04 16:24:48', NULL);
......@@ -584,6 +584,8 @@ INSERT INTO `sys_roles_menus` VALUES (19, 1);
INSERT INTO `sys_roles_menus` VALUES (21, 1);
INSERT INTO `sys_roles_menus` VALUES (22, 1);
INSERT INTO `sys_roles_menus` VALUES (23, 1);
INSERT INTO `sys_roles_menus` VALUES (24, 1);
INSERT INTO `sys_roles_menus` VALUES (27, 1);
INSERT INTO `sys_roles_menus` VALUES (28, 1);
INSERT INTO `sys_roles_menus` VALUES (30, 1);
INSERT INTO `sys_roles_menus` VALUES (32, 1);
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment