Java连接redis + springboot整合redis+使用redis作为缓存

文章详细介绍了Java如何连接Redis,包括单机模式、连接池以及集群模式。同时,文章探讨了Springboot整合Redis的方式,展示了如何使用RedisTemplate进行各种数据类型的操作。此外,还讨论了Redis作为缓存的使用,包括缓存注解和自定义AOP缓存实现。
摘要由CSDN通过智能技术生成

目录

1.Java连接redis

1.1. Java连接单机redis

(1)引入依赖

 (2)测试

1.2. java通过连接池连接redis

1.3.性能测试

1.4.java连接redis集群

2.springboot整合redis

2.1.spring boot下redis常用命令

2.2.Springboot操作redis

3.springboot使用redis集群模式

4.使用redis作为缓存

4.1.实现缓存

4.2.使用缓存注解

4.3.使用自定义注解和aop缓存



1.Java连接redis

1.1. Java连接单机redis

创建一个普通的maven工程

(1)引入依赖
<dependencies>
         <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
             <version>3.8.0</version>
        </dependency>
    </dependencies>
 (2)测试
public class TestDemo01 {

    @Test
    public void test01() {
        //所有的redis的操作都封装到一个Jedis类中
        Jedis jedis = new Jedis("192.168.75.129", 6379);//默认连接本机redis 端口6379

        //key操作

        String set = jedis.set("k1", "v1");
        System.out.println("添加===="+set);
        Set<String> keys = jedis.keys("*");
        System.out.println("所有的key===="+keys);

        Boolean k2 = jedis.exists("k2");
        System.out.println("k2是否存在===="+k2);

        Long k1 = jedis.del("k1");
        System.out.println("删除指定key====="+k1);

        Long k3 = jedis.expire("k2", 10);
        System.out.println("10s后自动删除===="+k3);

        String select = jedis.select(2);
        System.out.println("选择库2===="+select);

        String s = jedis.flushDB();
        System.out.println("清空当前库===="+s);


        //String 字符串类型
        jedis.setex("k9",20,"cjj");
        String k9 = jedis.get("k9");
        System.out.println(k9);
        Long setnx = jedis.setnx("k10", "ccc");
        System.out.println(setnx);
        String set2 = jedis.set("k1", "v1");
        System.out.println(set2);
        String k = jedis.get("k1");
        System.out.println("获取k1对应的value值===="+k);
        String mset = jedis.mset("k2", "v2", "k3", "v3");
        System.out.println("一次存储多个字符串类型value===="+mset);
        List<String> mget = jedis.mget("k2", "k3");
        System.out.println("一次获取多个value===="+mget);

        //hash类型的操作
        jedis.hset("k20","name","迪丽热巴");
        String hget = jedis.hget("k20", "name");
        System.out.println(hget);

        Map<String,String> map = new HashMap<>();
        map.put("name","古力娜扎");
        map.put("age","25");
        map.put("sex","女");
        jedis.hset("k30",map);
        Map<String, String> map1 = jedis.hgetAll("k30");
        System.out.println(map1.get("name"));

        //list类型
        Long lpush = jedis.lpush("k40", "v40", "v41", "v2");
        System.out.println(lpush);
        String k40 = jedis.lindex("k40", 1);
        System.out.println("下标1的==="+k40);
        String lset = jedis.lset("k40", 0, "v001");
        System.out.println(lset);
        List<String> k401 = jedis.lrange("k40", 0, -1);
        System.out.println(k401);

        //set操作
        Long sadd = jedis.sadd("k01", "v01", "v02", "v03");
        System.out.println(sadd);
        Set<String> k01 = jedis.smembers("k01");
        System.out.println(k01);

        //sorted set 操作
        Long zadd = jedis.zadd("k02", 10.0, "aa");
        Set<String> k02 = jedis.zrange("k02", 0, -1);
        System.out.println(k02);


        jedis.close();
    }
}

特点: Jedis把对redis的操作都封装到Jedis类对象中了,而每个命令封装了一个对应的方法。

1.2. java通过连接池连接redis

连接池的作用: 减少频繁创建和销毁连接对象

   //创建jedis连接池的配置
    @Test
    public void test02() {
        //创建jedis连接池的配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10); //最大值
        jedisPoolConfig.setMinIdle(5);//最小空闲值
        jedisPoolConfig.setMaxIdle(8);//最大空闲值
        jedisPoolConfig.setTestOnBorrow(true);//拿到jedis对象时,是否验证该对象可用
        jedisPoolConfig.setMaxWaitMillis(3000); //等待时间   3s

        //创建jedis连接池
        JedisPool jedisPool = new JedisPool(jedisPoolConfig,"192.168.75.129",6379);


        //获取jedis连接对象
        Jedis jedis = jedisPool.getResource();

        //key操作
        String set = jedis.set("k1", "v1");
        System.out.println("添加===="+set);
        Set<String> keys = jedis.keys("*");
        System.out.println("所有的key===="+keys);
    }

1.3.性能测试

结论:连接池性能高

 //测试:使用连接池
    @Test
    public void test03() {
        //创建jedis连接池的配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10); //最大值
        jedisPoolConfig.setMinIdle(5);//最小空闲值
        jedisPoolConfig.setMaxIdle(8);//最大空闲值
        jedisPoolConfig.setTestOnBorrow(true);//拿到jedis对象时,是否验证该对象可用
        jedisPoolConfig.setMaxWaitMillis(3000); //等待时间   3s
        //创建jedis连接池
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, "192.168.75.129", 6379);
        //测试:写一个for循环测试一个循环100次需要多少时间
        long start = System.currentTimeMillis();
        for (int i=0 ; i<100 ; i++){
            //获取jedis连接对象
            Jedis jedis = jedisPool.getResource();
            String ping =jedis.ping();
            System.out.println(ping);
            jedis.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("用时===="+(end-start));
    }
使用Jedis类
 @Test
    public void test04() {
        //测试:写一个for循环测试一个循环100次需要多少时间
        long start = System.currentTimeMillis();
        for (int i=0 ; i<100 ; i++){
            //获取jedis连接对象
            Jedis jedis = new Jedis("192.168.75.129", 6379);
            String ping =jedis.ping();
            System.out.println(ping);
            jedis.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("用时===="+(end-start));
    }

1.4.java连接redis集群

public class Test04 {
    public static void main(String[] args) {
        //必须时所有redis服务器
        HostAndPort hostAndPort1=new HostAndPort("192.168.223.147",7001);
        HostAndPort hostAndPort2=new HostAndPort("192.168.223.147",7002);
        HostAndPort hostAndPort3=new HostAndPort("192.168.223.147",7003);
        HostAndPort hostAndPort4=new HostAndPort("192.168.223.147",7004);
        HostAndPort hostAndPort5=new HostAndPort("192.168.223.147",7005);
        HostAndPort hostAndPort6=new HostAndPort("192.168.223.147",7006);
        Set<HostAndPort> sets=new HashSet<HostAndPort>();
        sets.add(hostAndPort1);
        sets.add(hostAndPort2);
        sets.add(hostAndPort3);
        sets.add(hostAndPort4);
        sets.add(hostAndPort5);
        sets.add(hostAndPort6);
        JedisCluster jedisCluster=new JedisCluster(sets);
        jedisCluster.set("k1","v1");
        jedisCluster.set("k2","v2");
        jedisCluster.set("k3","v3");
        jedisCluster.set("k4","v4");
        jedisCluster.set("k5","v5");
        jedisCluster.set("k6","v6");
        jedisCluster.set("k7","v7");

    }
}

2.springboot整合redis

springboot操作redis.封装了俩个类RedisTemplate和StringRedisTemplate,

而StringRedistemplate它是redisTemplate的子类,它只能对字符串操作。

如果想通过该StringRedistemplate放入一个对象时,

需要把该对象转换为json字符串才能放入

(1)创建一个Springboot工程

(2)引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.13</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-redis</name>
    <description>springboot-redis</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <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>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

(2)配置信息application.properties

#redis的配置信息--单机
spring.redis.host=192.168.75.129
spring.redis.port=6379

2.1.spring boot下redis常用命令

spring boot对redis进行了封装变成了RedisTemplate,所以在使用的时候不像以前注入JedisPool了,而是变成了RedisTemplate。

(3)测试

package com.wqg;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@SpringBootTest
class SpringbootRedisApplicationTests {

    //springboot创建好该类对象 并交于IOC容器管理
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    void test01() {
        //1.操作redis服务---key操作
        Boolean k1 = redisTemplate.delete("k1"); //删除指定key
        System.out.println(k1);
       
        Boolean hasKey = redisTemplate.hasKey("k1");//判断指定的key是否存在
        System.out.println(hasKey);
        
        Set<String> keys = redisTemplate.keys("*");
        System.out.println("所有key==="+keys);
      
        System.out.println("========================================================================================");


        //string操作
        //redisTemplate对每一种类型的操作单独封装了相应的类---由相应类对象操作相应数据类型
        ValueOperations<String, String> forValue = redisTemplate.opsForValue();//操作字符串
      
        forValue.set("k1","v1",30, TimeUnit.SECONDS); //存在30s
        
        String k11 = forValue.get("k1");
        System.out.println(k11);
       
        Boolean k2 = forValue.setIfAbsent("k2", "666", 30, TimeUnit.SECONDS);//指定key存在,存储失败
        System.out.println(k2);
        
        System.out.println("========================================================================================");

        //List类型
        ListOperations<String, String> forList = redisTemplate.opsForList();

        Long aLong = forList.leftPush("k100", "v111");//从左往指定key集合中设置value
        System.out.println(aLong);
        String k100 = forList.leftPop("k100");//获取指定key值集合左侧的一个元素
        System.out.println(k100);
       
        //从左往指定key集合中设置多个value
        Long aLong1 = forList.leftPushAll("k100", "v01", "v02", "v03");
        System.out.println(aLong1);
       
        //获取指定key值集合中从指定下标开始到指定下标结束的所有元素的集合
        List<String> k1001 = forList.range("k100", 0, 2);
        System.out.println(k1001);
        
        //删除指定key集合中值等于value的元素(count=0, 删除所有值等于value的元素; count>0, 从头部开始删除第一个值等于value的元素; count<0, 从尾部开始删除第一个值等于value的元素)
        Long remove = forList.remove("k100", 0, "v01");
        System.out.println(remove);
       
        System.out.println("========================================================================================");

        //hash类型操作
        HashOperations<String, Object, Object> forHash = redisTemplate.opsForHash();
        
        forHash.put("k03","name","cjj");
        forHash.put("k03","age","25");
        Object o = forHash.get("k03", "name");
        System.out.println("name值==="+o);

        Set<Object> k031 = forHash.keys("k03");
        System.out.println("hashKey对应的值==="+k031);

        Long delete = forHash.delete("k03", "name");
        System.out.println("删除name==="+delete);

        Boolean hasKey1 = forHash.hasKey("k03", "name");
        System.out.println(hasKey1); //判断name是否存在

        Map<Object, Object> k03 = forHash.entries("k03");
        System.out.println("k03所有==="+k03);
        
        System.out.println("========================================================================================");
        
        //set类型
        SetOperations<String, String> forSet = redisTemplate.opsForSet();
        
        Long add = forSet.add("k22", "v22","v33","v44","v55");//存储
        System.out.println(add);
        
        Long add2 = forSet.add("k33", "v21","v33","v41","v55");//存储
        System.out.println(add2);
        
        Long remove1 = forSet.remove("k22", "v33");
        System.out.println("删除==="+remove1);
        
        Set<String> k22 = forSet.members("k22");
        System.out.println("所有value==="+k22);
        
        Long k221 = forSet.size("k22");
        System.out.println("所有元素个数:"+k221);
        
        String k222 = forSet.randomMember("k22");
        System.out.println("随机一个元素==="+k222);
        
        Boolean member = forSet.isMember("k22", "v44");
        System.out.println("判断是否存在==="+member);
        
        String k223 = forSet.pop("k22");
        System.out.println("栈顶元素==="+k223);

        Set<String> difference = forSet.difference("k22", "k33");
        System.out.println("差值==="+difference);


    }

}

2.2.Springboot操作redis

(1)使用RedisTemplate时需要为key和value设置序列化 ---这里使用配置类

@Configuration
public class RedisConfig {
    @Bean //把该方法返回的类对象交于spring的IOC容器来管理
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化  filed value
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(redisSerializer); 
        return template;
    }
}

(2)测试:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Integer id;
    private String name;

}
package com.wqg;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

/**
 * @ fileName:redis02
 * @ description:
 * @ author:wqg
 * @ createTime:2023/7/3 20:49
 */
@SpringBootTest
public class redis02 {

    //springboot创建好该类对象 并交于IOC容器管理
    @Autowired
    private RedisTemplate redisTemplate; //在使用时需要指定序列化方式,如果没有指定,则采用JDK序列化方式,而jdk序列化方式要求类对象必须实现序列化接口

    //设置指定key value的序列号方式
    @Test
    public void test02(){
        redisTemplate.setKeySerializer(new GenericJackson2JsonRedisSerializer());//设置指定key的序列化方式
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());//设置指定value的序列化方式
        //可以操作字符串类型
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("k1","v1");
        System.out.println(valueOperations.get("k1"));

        valueOperations.set("k2",new User(1,"迪丽热巴"));
        System.out.println(valueOperations.get("k2"));
    }

    //===================================================================================================
    
    //难道我们每次使用都要指定序列化?可以弄一个配置类
    //使用配置类的方式设置序列化
    @Test
    public void test04(){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("k35",new User(33,"ssss"));
    }
}

3.springboot使用redis集群模式

application.properties配置文件添加:


#redis的配置信息--单机
spring.redis.host=192.168.75.129
spring.redis.port=6379

# nginx代理redis集群
spring.redis.cluster.nodes=192.168.75.129:7001,192.168.75.129:7002,192.168.75.129:7003,192.168.75.129:7004,192.168.75.129:7005,192.168.75.129:7006

测试:

4.使用redis作为缓存

缓存:---存在内存中。

作用: ---提高查询性能,减少数据库访问频率。

什么样的数据适合放入缓存: ---安全系数低的。---访问频率高 ---修改频率低 。

4.1.实现缓存

application.properties配置文件

spring.datasource.username=root
spring.datasource.password=123456789
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///qy165?serverTimezone=Asia/Shanghai

spring.redis.host=192.168.75.129
spring.redis.port=6379

mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

 RedisConfig 配置类

@Configuration
public class RedisConfig {
    @Bean //把该方法返回的类对象交于spring的IOC容器来管理
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);
        template.setConnectionFactory(factory);
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        //value hashmap序列化  filed value
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(redisSerializer); 
        return template;
    }
}

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "tbl_dept")
public class Dept {

    private Integer id;
    @TableField(value = "d_name")
    private String dName;
    private String loc;
}

dao层

public interface DeptDao extends BaseMapper<Dept> {
}

修改SpringbootRedisCacheApplication

@SpringBootApplication
@MapperScan(basePackages = "com.wqg.dao")
public class SpringbootRedisCacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootRedisCacheApplication.class, args);
    }

}

service层 实现缓存

package com.wqg.service;

import com.wqg.dao.DeptDao;
import com.wqg.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ fileName:DeptService
 * @ description:
 * @ author:wqg
 * @ createTime:2023/7/4 18:16
 */
@Service
public class DeptService {

    @Autowired
    private DeptDao deptDao;

    @Autowired
    private RedisTemplate redisTemplate;

    //根据id查询
    public Dept findById(Integer id) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //1.查询缓存是否存在该数据
        Object o = valueOperations.get("dept:" + id);
        if (o != null && o instanceof Dept) {
            return (Dept) o;
        }
        //2.查询数据库
        Dept dept = deptDao.selectById(id);
        if (dept != null) {
            //把该数据放入缓冲中
            valueOperations.set("dept:" + id, dept, 24, TimeUnit.HOURS);
        }
        return dept;
    }


    //修改
    public Dept update(Dept dept) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //先改数据库再清缓存
        deptDao.updateById(dept);
        valueOperations.set("dept:" + dept.getId(), dept);
        return dept;
    }


    //添加
    public Dept insert(Dept dept) {
        deptDao.insert(dept);
        return dept;
    }

    //删除
    public int delete(int id) {
        redisTemplate.delete("dept:" + id);
        deptDao.deleteById(id);
        return 1;
    }
    
}

测试根据id查询是否出现缓存

@SpringBootTest
class SpringbootRedisCacheApplicationTests {

    @Autowired
    private DeptService deptService;

    //根据id查询
    @Test
    void contextLoads() {
        Dept byId = deptService.findById(1);
        System.out.println(byId);
    }

}

第一次执行走数据库,控制台会打印sql语句,第二种走缓存,不会打印sql语句

思考: AOP---可以把一些非核心业务代码抽象----抽取为一个切面类@Aspect. 在结合一些注解完成相应的切面功能。 Spring框也能想到,Spring在3.0以后提高了缓存注解。可以帮你把功能抽取。

4.2.使用缓存注解

(1)RedisConfig类中添加配置缓存配置

 @Bean
 public CacheManager cacheManager(RedisConnectionFactory factory) {
     RedisSerializer<String> redisSerializer = new StringRedisSerializer();
     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);
     // 配置序列化(解决乱码的问题),过期时间600秒
     RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
             .entryTtl(Duration.ofSeconds(600)) //缓存过期10分钟 ---- 业务需求。
             .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))//设置key的序列化方式
             .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) //设置value的序列化
             .disableCachingNullValues();
     RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
             .cacheDefaults(config)
             .build();
     return cacheManager;
 }

(2)开启缓存注解

(3)使用缓存注解

package com.wqg.service;

import com.wqg.dao.DeptDao;
import com.wqg.entity.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ fileName:DeptService
 * @ description:
 * @ author:wqg
 * @ createTime:2023/7/4 18:16
 */
@Service
public class DeptServiceCache {

    @Autowired
    private DeptDao deptDao;



    //先从缓存中找名字叫:cacheNames::key 如果存在,则方法不执行。如果不存在会执行方法,并把改方法的返回值作为缓存的值.
    //Cacheable查询的缓存注解: 缓存的名称叫做: cacheNames::key
    @Cacheable(cacheNames = "dept",key="#id")
    public Dept findById(Integer id) {
        //2.查询数据库
        Dept dept = deptDao.selectById(id);
        return dept;
    }


    //先执行方法体,并把方法的返回结果作为缓存的值。修改缓存的值。
    @CachePut(cacheNames = "dept",key="#dept.id")
    public Dept update(Dept dept){
        //1.先该数据库还是先删缓冲。
        deptDao.updateById(dept);
        return dept;
    }

    //添加没有缓存注解......

    //删除缓存再执行方法体
    @CacheEvict(cacheNames = "dept",key = "#id")
    public int delete(int id){
        deptDao.deleteById(id);
        return 1;
    }
}

(4)测试

package com.wqg;

import com.wqg.entity.Dept;
import com.wqg.service.DeptService;
import com.wqg.service.DeptServiceCache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootRedisCacheApplicationTests2 {

    @Autowired
    private DeptServiceCache deptService;

    //根据id查询
    @Test
    void test01() {
        Dept byId = deptService.findById(2);
        System.out.println(byId);
    }

    //修改
    @Test
    void test02() {
        Dept dept = new Dept();
        dept.setId(2);
        dept.setDName("cjhj");
        dept.setLoc("asdas");
        Dept update = deptService.update(dept);
        System.out.println(update);
    }

    //删除
    @Test
    void test03() {
        int delete = deptService.delete(2);
        System.out.println(delete);
    }


}

4.3.使用自定义注解和aop缓存

基于4.2.改造

定义自定义注解

@Target(value=ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCacheable {
    String cacheName();
}

定义aop切面类

@Component
@Aspect
public class CacheAspect {
    @Pointcut(value = "@annotation(com.wqg.annotion.MyCacheable)")
    private void pointcut(){} //切点

    @Autowired
    private RedisTemplate redisTemplate;


    @Around("pointcut()")
    public Object arount(ProceedingJoinPoint joinPoint) throws Throwable { //连接点
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod(); //得到被切入的方法对象
        MyCacheable annotation = method.getAnnotation(MyCacheable.class);//得到方法上的注解对象
        String cacheName = annotation.cacheName(); //获取注解cacheName属性
        Object[] args = joinPoint.getArgs(); //获取改方法具有的参数
        if(args.length!=0){
              cacheName=cacheName+"::"+args[0]; //dept::
        }
        Object o = redisTemplate.opsForValue().get(cacheName);
        if(o!=null){
            return o;
        }

        Object result = joinPoint.proceed(); //执行被切入的方法
        if(result!=null){
            redisTemplate.opsForValue().set(cacheName,result); //放入redis
        }

        return result;
    }
}
创建MyDeptServiceCache
@Service
public class MyDeptServiceCache {

    @Autowired
    private DeptDao deptDao;

    @MyCacheable(cacheName = "dept")
    public Dept findById(Integer id){
        Dept dept = deptDao.selectById(id);
        return dept;
    }

}

测试

@SpringBootTest
class SpringbootRedisCacheApplicationTests3 {

   @Autowired
    private MyDeptServiceCache deptServiceCache;

   @Test
    void test(){
       Dept byId = deptServiceCache.findById(3);
       System.out.println(byId);
   }

}

结果:从数据库获取

 再次访问结果:从缓存获取的

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值