SpringBoot集成Spring Cache 和 Redis

pom:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
         
    
    com.example
    redisdemo
    0.0.1-SNAPSHOT
    redisdemo
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            junit
            junit
            RELEASE
        
        
            org.springframework
            spring-test
            RELEASE
        
        
            org.springframework.boot
            spring-boot-test
            RELEASE
        
        
        
            com.alibaba
            fastjson
            1.2.47
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



在application.properties中指定redis服务器IP、端口和密码、连接数等:

Redis服务器地址

spring.redis.host=127.0.0.1

Redis服务器连接端口 使用默认端口6379可以省略配置

spring.redis.port=6379

Redis服务器连接密码(默认为空)

spring.redis.password=

连接池最大连接数(如果配置<=0,则没有限制 )

spring.redis.jedis.pool.max-active=8

java

package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootCacheApplicationTests {

    @Autowired
    StringRedisTemplate stringRedisTemplate; //操作 k-v 字符串

    /**
     * redis 常见
     * String(字符串) List(列表) Set(集合) Hash(散列) ZSet(有序集合)
     */

    @Test
    public void testAddString() {
        stringRedisTemplate.opsForValue().set("StringKey", "字符串数值");
        String value = stringRedisTemplate.opsForValue().get("StringKey");
        System.out.println(value);
    }

    @Test
    public void testAddObject() {
        Person person = new Person("张三",33);
        String jsonPerson = JSON.toJSONString(person);
        stringRedisTemplate.opsForValue().set("person_1", jsonPerson);
        String value = stringRedisTemplate.opsForValue().get("person_1");
        Person pp = JSON.parseObject(value, new TypeReference() {});
        System.out.println(pp.getName());
    }

    @Test
    public void testDel() {
        stringRedisTemplate.delete("StringKey");
    }

    @Test
    public void testExpire() {
        Person person = new Person("张三",33);
        String jsonPerson = JSON.toJSONString(person);
        stringRedisTemplate.opsForValue().set("person_1", jsonPerson,60,
                TimeUnit.SECONDS);
        String value = stringRedisTemplate.opsForValue().get("person_1");
        Person pp = JSON.parseObject(value, new TypeReference() {});
        System.out.println(pp.getName());
    }
}

Person.java

package com.example.demo;

/**
 * Created by Administrator on 2019/3/29.
 */
public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Spring Cache

Spring Cache使用方法与Spring对事务管理的配置相似。Spring Cache的核心就是对某个方法进行缓存,其实质就是缓存该方法的返回结果,并把方法参数和结果用键值对的方式存放到缓存中,当再次调用该方法使用相应的参数时,就会直接从缓存里面取出指定的结果进行返回:
常用注解:
@Cacheable-------使用这个注解的方法在执行后会缓存其返回结果。
@CacheEvict--------使用这个注解的方法在其执行前或执行后移除Spring Cache中的某些元素。

TestService

package com.example.demo;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * Created by Administrator on 2019/3/29.
 */
//hello::600
@Service
public class TestService {
    @Cacheable(value="person",key="#id")
    public Person findById(String id)
    {
        System.out.println("---------------------");
        Person person = new Person("张三",33);

        return person;
    }

    @CacheEvict(value="person",key="#person.age")
    public void update(Person person) {
//        gatheringDao.save(gathering);
        System.out.println("update");
    }

    @CacheEvict(value="person",key="#id")
    public void deleteById(String id) {
        System.out.println("deleteById 从数据库中删除了该对象");
    }

}

SpringbootCacheApplicationTests

package com.example.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@SpringBootTest
@EnableCaching
public class SpringbootCacheApplicationTests {

    @Autowired
    StringRedisTemplate stringRedisTemplate; //操作 k-v 字符串

    @Autowired
    TestService testService;
    /**
     * redis 常见
     * String(字符串) List(列表) Set(集合) Hash(散列) ZSet(有序集合)
     */

    @Test
    public void testAddString() {
        stringRedisTemplate.opsForValue().set("StringKey", "字符串数值");
        String value = stringRedisTemplate.opsForValue().get("StringKey");
        System.out.println(value);
    }

    @Test
    public void testAddObject() {
//        String value = stringRedisTemplate.opsForValue().get("person_18");
//        System.out.println(value);
//        if(value == null)
//        {
//            //mybatis查数据库,得到person对象
//        }
//        else
//        {
//            Person pp = JSON.parseObject(value, new TypeReference() {});
//        }

        Person person = new Person("张三",33);
        String jsonPerson = JSON.toJSONString(person);
        stringRedisTemplate.opsForValue().set("person_1", jsonPerson);
        String value = stringRedisTemplate.opsForValue().get("person_1");
        Person pp = JSON.parseObject(value, new TypeReference() {});
        System.out.println(pp.getName());
    }

    @Test
    public void testDel() {
        stringRedisTemplate.delete("StringKey");
    }

    @Test
    public void testExpire() {
        Person person = new Person("张三",33);
        String jsonPerson = JSON.toJSONString(person);
        stringRedisTemplate.opsForValue().set("person_1", jsonPerson,60,
                TimeUnit.SECONDS);
        String value = stringRedisTemplate.opsForValue().get("person_1");
        Person pp = JSON.parseObject(value, new TypeReference() {});
        System.out.println(pp.getName());
    }

    @Test
    public void testCache() {
        Person person = testService.findById("33");
        System.out.println(person.getName());
    }

    @Test
    public void testCacheDel() {
        testService.deleteById("33");

    }

    @Test
    public void testCacheUpdate() {
        Person person = new Person("haha",33);
        testService.update(person);

    }
}

Person

package com.example.demo;

import java.io.Serializable;

/**
 * Created by Administrator on 2019/3/29.
 */

public class Person implements Serializable{
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

你可能感兴趣的:(SpringBoot集成Spring Cache 和 Redis)