[代码优化](v2.5): 代码优化,缓存优化

pull/455/head
ZhengJie 2020-06-21 17:24:14 +08:00
parent 6bc2a8ada1
commit 96660b949d
14 changed files with 64 additions and 106 deletions

View File

@ -15,11 +15,10 @@
*/
package me.zhengjie.utils;
/**
* @author: liaojinlong
* @date: 2020/6/11 15:49
* @apiNote: Key
* @apiNote: Key
*/
public interface CacheKey {
@ -39,7 +38,7 @@ public interface CacheKey {
String USER_ID = "user::id:";
String USER_NAME = "user::username:";
/**
* s
*
*/
String DATE_USER = "data::user:";
/**
@ -50,6 +49,8 @@ public interface CacheKey {
*
*/
String ROLE_AUTH = "role::auth:";
/**
*
*/
String ROLE_ID = "role::id:";
}

View File

@ -26,14 +26,15 @@ import java.util.Date;
* @apiNote: JDK 8
*/
public class DateUtil {
public static final DateTimeFormatter dfyMdHms = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static final DateTimeFormatter dfyMd = DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static final DateTimeFormatter DFY_MD_HMS = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static final DateTimeFormatter DFY_MD = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/**
* LocalDateTime
*
* @param localDateTime
* @return/
* @param localDateTime /
* @return /
*/
public static Long getTimeStamp(LocalDateTime localDateTime) {
return localDateTime.atZone(ZoneId.systemDefault()).toEpochSecond();
@ -42,8 +43,8 @@ public class DateUtil {
/**
* LocalDateTime
*
* @param timeStamp
* @return/
* @param timeStamp /
* @return /
*/
public static LocalDateTime fromTimeStamp(Long timeStamp) {
return LocalDateTime.ofEpochSecond(timeStamp, 0, OffsetDateTime.now().getOffset());
@ -53,8 +54,8 @@ public class DateUtil {
* LocalDateTime Date
* Jdk8 使 {@link Date} Date
*
* @param localDateTime
* @return/
* @param localDateTime /
* @return /
*/
public static Date toDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
@ -64,8 +65,8 @@ public class DateUtil {
* LocalDate Date
* Jdk8 使 {@link Date} Date
*
* @param localDate
* @return/
* @param localDate /
* @return /
*/
public static Date toDate(LocalDate localDate) {
return toDate(localDate.atTime(LocalTime.now(ZoneId.systemDefault())));
@ -76,8 +77,8 @@ public class DateUtil {
* Date LocalDateTime
* Jdk8 使 {@link Date} Date
*
* @param date
* @return/
* @param date /
* @return /
*/
public static LocalDateTime toLocalDateTime(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
@ -86,9 +87,9 @@ public class DateUtil {
/**
*
*
* @param localDateTime
* @param patten
* @return/
* @param localDateTime /
* @param patten /
* @return /
*/
public static String localDateTimeFormat(LocalDateTime localDateTime, String patten) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(patten);
@ -98,9 +99,9 @@ public class DateUtil {
/**
*
*
* @param localDateTime
* @param df
* @return/
* @param localDateTime /
* @param df /
* @return /
*/
public static String localDateTimeFormat(LocalDateTime localDateTime, DateTimeFormatter df) {
return df.format(localDateTime);
@ -109,28 +110,28 @@ public class DateUtil {
/**
* yyyy-MM-dd HH:mm:ss
*
* @param localDateTime
* @return/
* @param localDateTime /
* @return /
*/
public static String localDateTimeFormatyMdHms(LocalDateTime localDateTime) {
return dfyMdHms.format(localDateTime);
return DFY_MD_HMS.format(localDateTime);
}
/**
* yyyy-MM-dd
*
* @param localDateTime
* @return/
* @param localDateTime /
* @return /
*/
public String localDateTimeFormatyMd(LocalDateTime localDateTime) {
return dfyMd.format(localDateTime);
return DFY_MD.format(localDateTime);
}
/**
* LocalDateTime yyyy-MM-dd
*
* @param localDateTime
* @return/
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
@ -140,30 +141,20 @@ public class DateUtil {
/**
* LocalDateTime yyyy-MM-dd
*
* @param localDateTime
* @return/
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) {
return LocalDateTime.from(dateTimeFormatter.parse(localDateTime));
}
/**
* LocalDateTime yyyy-MM-dd
*
* @param localDateTime
* @return/
*/
public static LocalDateTime parseLocalDateTimeFormatyMd(String localDateTime) {
return LocalDateTime.from(dfyMd.parse(localDateTime));
}
/**
* LocalDateTime yyyy-MM-dd HH:mm:ss
*
* @param localDateTime
* @return/
* @param localDateTime /
* @return /
*/
public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) {
return LocalDateTime.from(dfyMdHms.parse(localDateTime));
return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime));
}
}

View File

@ -16,7 +16,6 @@
package me.zhengjie.modules.security.rest;
import cn.hutool.core.util.IdUtil;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.base.Captcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -38,7 +37,6 @@ import me.zhengjie.utils.RsaUtils;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -47,7 +45,6 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
@ -91,7 +88,6 @@ public class AuthorizationController {
}
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(authUser.getUsername(), password);
Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
// 生成令牌

View File

@ -93,8 +93,8 @@ public class TokenFilter extends GenericFilterBean {
/**
* Token
*
* @param request
* @return
* @param request /
* @return /
*/
private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(properties.getHeader());

View File

@ -52,7 +52,6 @@ public class TokenProvider implements InitializingBean {
private final SecurityProperties properties;
private final RedisUtils redisUtils;
public static final String AUTHORITIES_KEY = "auth";
private Key key;
private JwtParser jwtParser;
private JwtBuilder jwtBuilder;
@ -64,7 +63,7 @@ public class TokenProvider implements InitializingBean {
@Override
public void afterPropertiesSet() {
byte[] keyBytes = Decoders.BASE64.decode(properties.getBase64Secret());
this.key = Keys.hmacShaKeyFor(keyBytes);
Key key = Keys.hmacShaKeyFor(keyBytes);
jwtParser = Jwts.parserBuilder()
.setSigningKey(key)
.build();
@ -76,11 +75,11 @@ public class TokenProvider implements InitializingBean {
* Token
* Token Redis
*
* @param authentication
* @return
* @param authentication /
* @return /
*/
public String createToken(Authentication authentication) {
/**
/*
*
*/
String authorities = authentication.getAuthorities().stream()
@ -98,8 +97,8 @@ public class TokenProvider implements InitializingBean {
/**
* Token
*
* @param token
* @return
* @param token /
* @return /
*/
Authentication getAuthentication(String token) {
Claims claims = getClaims(token);

View File

@ -27,12 +27,11 @@ import org.springframework.stereotype.Component;
@Component
public class UserCacheClean {
/**
* <br>
*
*
* @param userName
* @param userName /
*/
public void cleanUserCache(String userName) {
if (StringUtils.isNotEmpty(userName)) {

View File

@ -27,7 +27,6 @@ import me.zhengjie.modules.system.service.dto.UserDto;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ -42,7 +41,6 @@ public class UserDetailsServiceImpl implements UserDetailsService {
private final RoleService roleService;
private final DataService dataService;
private final LoginProperties loginProperties;
public void setEnableCache(boolean enableCache) {
this.loginProperties.setCacheEnable(enableCache);
}

View File

@ -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;

View File

@ -117,7 +117,7 @@ public class RoleServiceImpl implements RoleService {
role.setLevel(resources.getLevel());
roleRepository.save(role);
// 更新相关缓存
delCaches(role.getId());
delCaches(role.getId(), null);
}
@Override
@ -126,11 +126,10 @@ public class RoleServiceImpl implements RoleService {
List<User> users = userRepository.findByRoleId(role.getId());
// 更新菜单
role.setMenus(resources.getMenus());
cleanCache(resources, users);
delCaches(resources.getId(), users);
roleRepository.save(role);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void untiedMenu(Long menuId) {
@ -143,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);
}
@ -208,40 +207,18 @@ public class RoleServiceImpl implements RoleService {
/**
*
*
* @param id /
*/
public void delCaches(Long id) {
List<User> users = userRepository.findByRoleId(id);
public void delCaches(Long id, List<User> users) {
users = CollectionUtil.isEmpty(users) ? userRepository.findByRoleId(id) : users;
if (CollectionUtil.isNotEmpty(users)) {
users.stream().forEach(item -> {
userCacheClean.cleanUserCache(item.getUsername());
});
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);
}
}
/**
*
*
* @param resources
* @param users
*/
private void cleanCache(Role resources, List<User> 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.MENU_USER, userIds);
redisUtils.delByKeys(CacheKey.ROLE_AUTH, userIds);
redisUtils.del(CacheKey.ROLE_ID + resources.getId());
}
}
}

View File

@ -235,7 +235,7 @@ public class UserServiceImpl implements UserService {
/**
*
*
* @param username
* @param username /
*/
private void flushCache(String username) {
userCacheClean.cleanUserCache(username);

View File

@ -5,19 +5,19 @@ 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;
private int size = 10000;
@Test
public void testCache() {
long start1 = System.currentTimeMillis();
int size = 10000;
for (int i = 0; i < size; i++) {
userDetailsService.loadUserByUsername("admin");
}
@ -29,6 +29,6 @@ public class LoginCacheTest {
userDetailsService.loadUserByUsername("admin");
}
long end2 = System.currentTimeMillis();
System.out.printf("使用缓存:" + (end1 - start1) + "毫秒\n 不使用缓存:" + (end2 - start2) + "毫秒");
System.out.print("使用缓存:" + (end1 - start1) + "毫秒\n 不使用缓存:" + (end2 - start2) + "毫秒");
}
}

View File

@ -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);

View File

@ -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);

View File

@ -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);