springboot自定义redisTemplate

1.添加springboot和redis的相关依赖

        <!-- 操作redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2.在springboot的yml配置文件中配置redis,注意:此处配置的redis的ip地址以及端口号是自己所安装的redis的ip以及端口号

spring:
  redis:
    port: 6379
    host: 192.168.45.26

3.创建config目录,自定义redisTemplate

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.StringRedisSerializer;

@Configuration
public class RedisConfig {
    //编写我们的redisTemplate
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        //为了方便,泛型规定为String,Object类型
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        //序列化 json解析任意对象
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);

        //使用ObjectMapper转义
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        //String的序列化
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);

        //hash的key也采用String 的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);

        //value采用jackson的序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);

        //hash的value也采用jackson的序列化方式
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }
}

4.创建一个单元测试方法,进行测试。注意:在进行测试时,一定要先启动redis服务,否则会报错

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lz.pojo.User;
import com.lz.utils.RedisUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;

@SpringBootTest
class RedisSpringbootApplicationTests {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;


    @Test
    void contextLoads() {
        /*
             redisTemplate 操作不同的数据类型,qpi和我们的指令是一样的
             opsForValue 操作字符串,类似于String
             opsForList  操作List,类似于List
             opsForHash
             opsForSet
             opsForZSet
             opsForGeo
             opsForHyperLogLog
        */

        // 除了基本的操作,常用的方法都可以通过redisTemplate操作,比如事务和基本的CRUD


        // 获取redis的连接对象
//        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//        connection.flushDb();
//        connection.flushAll();

        redisTemplate.opsForValue().set("key","科比");
        System.out.println(redisTemplate.opsForValue().get("key"));

    }

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于SpringBoot自定义Redis注解AOP的问题,我可以为您提供一些基本的介绍和示例代码。 Redis作为一种高性能的缓存和数据存储解决方案,被广泛应用于各种应用程序中。在SpringBoot应用程序中,使用Redis通常需要编写大量的重复代码,比如获取Redis连接、执行Redis命令、释放Redis连接等。这些重复代码不仅增加了开发和维护的难度,还影响了应用程序的性能。而AOP作为一种切面编程的技术,可以很好地解决这些问题。 下面是一个简单的示例代码,演示如何通过自定义注解实现对Redis操作的AOP处理: 首先,定义一个自定义注解: ```java @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RedisCacheable { String key() default ""; long expire() default 0; } ``` 然后,在需要被拦截的方法上添加该注解: ```java @Component public class RedisService { @Autowired private RedisTemplate<String, String> redisTemplate; @RedisCacheable(key = "myKey", expire = 60) public String getValue() { return redisTemplate.opsForValue().get("myKey"); } } ``` 接下来,使用AspectJ的@Aspect注解定义一个切面类,并在该类中定义一个切点,用于匹配被@RedisCacheable注解的方法: ```java @Aspect @Component public class RedisAspect { @Autowired private RedisTemplate<String, String> redisTemplate; @Pointcut("@annotation(com.example.demo.annotation.RedisCacheable)") public void redisCacheablePointcut() {} @Around("redisCacheablePointcut()") public Object aroundRedisCacheable(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); RedisCacheable redisCacheable = method.getAnnotation(RedisCacheable.class); String key = redisCacheable.key(); long expire = redisCacheable.expire(); String value = redisTemplate.opsForValue().get(key); if (value != null) { return value; } Object result = joinPoint.proceed(); if (result != null) { redisTemplate.opsForValue().set(key, result.toString()); if (expire > 0) { redisTemplate.expire(key, expire, TimeUnit.SECONDS); } } return result; } } ``` 在该切面类中,使用@Around注解定义一个环绕通知,在该通知中,首先获取被拦截方法上的@RedisCacheable注解,然后根据注解中的key值从Redis中获取数据。如果Redis中已经存在该数据,则直接返回;否则,执行被拦截方法,并将结果存储到Redis缓存中。 最后,启动SpringBoot应用程序,调用RedisService的getValue方法,就可以看到输出结果: ```java // 第一次调用,从数据库中获取数据,并将数据存入Redis缓存中 getValue... // 第二次调用,直接从Redis中获取数据 getValue... ``` 以上就是一个简单的SpringBoot自定义Redis注解AOP的示例。通过使用自定义注解和AOP技术,可以更加方便地实现对Redis缓存的操作,并提高应用程序的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值