Commit fd9c4a7a authored by liming's avatar liming

feat(初始化项目): 增加缓存和登录用户注入

parent 6fe0379a
......@@ -26,6 +26,20 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
......@@ -50,5 +64,20 @@
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
</dependency>
<dependency>
<groupId>com.antai.sport.http.server</groupId>
<artifactId>profile</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.antai.sport.http.server</groupId>
<artifactId>repository</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.antai.sport.http.server</groupId>
<artifactId>constants</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.antai.sport.http.server.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Author liming
* @Date 2021/8/23 1:59
* @Email lmmax@126.com
* @Description:
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginSportUser {
}
package com.antai.sport.http.server.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* @author liming on 2018/12/14.
*/
@Configuration
@EnableCaching
@ConfigurationProperties(prefix = "spring.cache.redis")
public class RedisCacheConfig extends CachingConfigurerSupport {
private Duration timeToLive = Duration.ZERO;
public void setTimeToLive(Duration timeToLive) {
this.timeToLive = timeToLive;
}
@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(this.timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
.disableCachingNullValues();
return RedisCacheManager.builder(connectionFactory)
.cacheDefaults(config)
.transactionAware()
.build();
}
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(keySerializer());
redisTemplate.setHashKeySerializer(keySerializer());
redisTemplate.setValueSerializer(valueSerializer());
redisTemplate.setHashValueSerializer(valueSerializer());
return redisTemplate;
}
private RedisSerializer<String> keySerializer() {
return new StringRedisSerializer();
}
private RedisSerializer<Object> valueSerializer() {
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
om.registerModule(new JavaTimeModule());
serializer.setObjectMapper(om);
return serializer;
}
}
package com.antai.sport.http.server.common.resolver;
import com.antai.sport.http.server.common.exception.BusinessException;
import com.antai.sport.http.server.common.jwt.TokenService;
import com.antai.sport.http.server.repository.sport.entity.SportUser;
import com.antai.sport.http.server.repository.sport.mapper.SportUserCacheMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.annotation.Resource;
public class SportUserArgumentResolver implements HandlerMethodArgumentResolver {
@Value("${project.header-token-key}")
private String headerTokenKey;
@Value("${project.jwt.subject-key}")
private String subjectKey;
@Resource
private SportUserCacheMapper sportUserCacheMapper;
@Resource
private TokenService tokenService;
/**
* 判断是否支持要转换的参数类型
*/
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().isAssignableFrom(SportUser.class);
}
/**
* 当支持后进行相应的转换 做业务操作
*/
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer modelAndViewContainer,
NativeWebRequest request,
WebDataBinderFactory webDataBinderFactory) throws Exception {
//从请求头中获参数信息
String token = request.getHeader(headerTokenKey);
if (token == null || token.isEmpty()) {
throw new BusinessException("token信息错误");
}
Claims claims = tokenService.validateToken(token);
if (claims == null) {
throw new BusinessException("token解析异常");
}
String phone = claims.get(subjectKey).toString();
SportUser sportUser = sportUserCacheMapper.getByPhone(phone);
if (sportUser == null) {
throw new BusinessException("当前用户不存在");
}
return sportUser;
}
}
......@@ -18,37 +18,11 @@
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.antai.sport.http.server</groupId>
<artifactId>profile</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.antai.sport.http.server</groupId>
<artifactId>repository</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.antai.sport.http.server</groupId>
<artifactId>common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.antai.sport.http.server</groupId>
<artifactId>constants</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
......
......@@ -3,6 +3,7 @@ package com.antai.sport.http.server.game.api;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.oas.annotations.EnableOpenApi;
......@@ -16,7 +17,7 @@ import springfox.documentation.oas.annotations.EnableOpenApi;
@SpringBootApplication
@EnableOpenApi
@ComponentScan(value = "com.antai")
@MapperScan("com.antai.**.repository")
@MapperScan("com.antai")
public class GameApiApplication {
public static void main(String[] args) {
SpringApplication.run(GameApiApplication.class, args);
......
package com.antai.sport.http.server.game.api.business.sport.user;
import com.antai.sport.http.server.common.annotation.LoginSportUser;
import com.antai.sport.http.server.common.base.Result;
import com.antai.sport.http.server.game.api.business.sport.user.dto.ReqLogin;
import com.antai.sport.http.server.repository.sport.entity.SportUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
......@@ -34,7 +36,8 @@ public class SportUserController {
}
@GetMapping("/test")
public ResponseEntity<Result> test() {
public ResponseEntity<Result> test(@LoginSportUser SportUser sportUser) {
System.out.println(1);
return success("test");
}
}
package com.antai.sport.http.server.game.api.config;
import com.antai.sport.http.server.common.resolver.SportUserArgumentResolver;
import com.antai.sport.http.server.game.api.interceptor.TokenInterceptor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
......@@ -44,6 +46,16 @@ public class WebMvcConfig implements WebMvcConfigurer {
return new TokenInterceptor();
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(sportUserArgumentResolver());
}
@Bean
SportUserArgumentResolver sportUserArgumentResolver() {
return new SportUserArgumentResolver();
}
public void setPermitUrl(List<String> permitUrl) {
this.permitUrl = permitUrl;
}
......
server:
port: 8080
spring:
profiles:
include:
- common-db-dev
redis:
database: 0
host: 127.0.0.1
port: 6379
password: 123
swagger:
enable: true
spring:
profiles:
include:
- common-db-prod
\ No newline at end of file
- common-db-prod
redis:
database: 0
host: 127.0.0.1
port: 6379
password: 123
\ No newline at end of file
......@@ -5,6 +5,22 @@ spring:
use-legacy-processing: true
profiles:
active: dev
cache:
redis:
use-key-prefix: true
time-to-live: 1d
redis:
timeout: 10s
jedis:
pool:
max-idle: 500
min-idle: 50
max-wait: -1s
max-active: -1
jackson:
date-format: com.antai.sport.http.server.common.jackson.StdDateFormat
time-zone: GMT+8
default-property-inclusion: always
project:
header-token-key: Authorization
......
......@@ -34,6 +34,7 @@
<jjwt.version>0.7.0</jjwt.version>
<jaxb.version>2.3.0</jaxb.version>
<activation.version>1.1.1</activation.version>
<commons.lang3.version>3.7</commons.lang3.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
......@@ -51,6 +52,11 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons.lang3.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
......
package com.antai.sport.http.server.repository.sport.mapper;
import com.antai.sport.http.server.repository.sport.entity.SportUser;
import org.springframework.cache.annotation.Cacheable;
/**
* @Author liming
* @Date 2021/8/23 0:59
* @Email lmmax@126.com
* @Description:
*/
public interface SportUserCacheMapper {
@Cacheable(value = "sport_user", key = "#p0", unless = "#result == null")
SportUser getByPhone(String username);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.antai.sport.http.server.repository.sport.mapper.SportUserCacheMapper">
<select id="getByPhone" parameterType="java.lang.String"
resultType="com.antai.sport.http.server.repository.sport.entity.SportUser">
select *
from sport_user t1
where t1.phone = #{username}
</select>
</mapper>
\ No newline at end of file
Markdown is supported
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