利用spring AOP封装高性能redis 查询框架,java @ 注解开发
1、创建 web 项目 spring boot + spring + Mybatis
相信想提升项目性能的同学应该有了一定的基础,如果不会创建项目的同学可以看我的另一篇文章,先上代码结构,有一些不需要的可以不关注
2、配置redis相关
导入redis 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
配置redis (yml):
// An highlighted block
#redis
redis:
database: 0
host: 127.0.0.1
#redis端口
port: 6379
#redis密码
password: 123456
timeout: 30000
ssl: false
配置完redis 后可以用spring 提供的 RedisTemplate操作redis,但是RedisTemplate默认的序列化方式采用的是jdk的默认格式,需要手动覆盖RedisTemplate k,y的序列化方式
// An highlighted block
package com.example.siyao.configure;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableAutoConfiguration
public class RedisConfig {
@Autowired
private RedisTemplate redisTemplate;
@Bean
public RedisTemplate redisCacheTemplate(LettuceConnectionFactory factory) {
redisTemplate.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
redisTemplate.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
redisTemplate.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
一定要@Autowired一个redisTemplate ,redisTemplate 下有一个实现类StringRedisTemplate,如果直接使用StringRedisTemplate,那么就不需要在覆盖redisTemplate,StringRedisTemplate已经覆盖了k,y的序列化方式,但是比较局限,因为一些hash的结构用json更合适
3、配置完成后我们导入spring aop 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
4、 创建controller
// An highlighted block
package com.example.siyao.controller;
import com.example.siyao.entity.User;
import com.example.siyao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/redis")
public class RedisController {
@Autowired
private UserService userService;
@RequestMapping("/user")
public void getUser(String uId){
User userById = userService.getUserById(uId);
System.out.println(userById);
}
}
5、 创建userService接口
// An highlighted block
package com.example.siyao.service;
import com.example.siyao.entity.User;
import org.springframework.stereotype.Service;
@Service
public interface UserService {
User getUserById(String uId);
}
6、 创建imp
// An highlighted block
package com.example.siyao.service.imp;
import com.example.siyao.common.cache.PrimaryKeyCache;
import com.example.siyao.entity.User;
import com.example.siyao.mapper.UserMapper;
import com.example.siyao.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserMapper userMapper;
@PrimaryKeyCache(key = "#uId")
public User getUserById(String uId) {
User usetById = userMapper.getUsetById(uId);
return usetById;
}
}
7、mapper
// An highlighted block
package com.example.siyao.mapper;
import com.example.siyao.entity.User;
import org.springframework.stereotype.Repository;
@Repository
public interface UserMapper {
User getUsetById(String uId);
}
8、 mapper.xml
// An highlighted block
<?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.example.siyao.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.siyao.entity.User">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="sex" jdbcType="VARCHAR" property="sex" />
</resultMap>
<select id="getUsetById" resultType="com.example.siyao.entity.User">
select * from tb_user where id = #{id}
</select>
</mapper>
9、 创建注解类
// An highlighted block
package com.example.siyao.common.cache;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义缓存注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PrimaryKeyCache {
String key();
}
10、 创建切面
// An highlighted block
package com.example.siyao.common.cache;
import com.example.siyao.entity.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;
import java.beans.DefaultPersistenceDelegate;
import java.lang.reflect.Method;
/**
* aop 程序 缓存
*/
@Component
@Aspect
public class CacheAespct {
@Autowired
private RedisTemplate redisTemplate;
@Around("@annotation(com.example.siyao.common.cache.PrimaryKeyCache)")
public Object queryCache(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("method execute before");
String keyEL = "";//动态key,匹配不同主键
MethodSignature signature = (MethodSignature) joinPoint.getSignature();//获得方法签名
Method method = joinPoint.getTarget().getClass().getMethod(signature.getName(), signature.getMethod().getParameterTypes());
PrimaryKeyCache annotation = method.getAnnotation(PrimaryKeyCache.class);
keyEL = annotation.key();
//1,create 解析器
ExpressionParser esxpressionParser = new SpelExpressionParser();
Expression expression = esxpressionParser.parseExpression(keyEL);
//2,设置解析上下文,(占位符..)
StandardEvaluationContext context = new StandardEvaluationContext();
//方法参数
Object[] args = joinPoint.getArgs();
DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(method);
for (int i = 0; i < parameterNames.length; i++){
context.setVariable(parameterNames[i],args[i]);
}
String key = expression.getValue(context).toString();
Object o = redisTemplate.opsForValue().get(key);
if(o != null){
System.out.println("In redis");
return (User) o;
}
Object proceed = joinPoint.proceed(); //execute method
redisTemplate.opsForValue().set(key,proceed);
System.out.println("In db");
System.out.println("method execute after");
return proceed;
}
}
test结果:
转载请注明出处!!!