美文网首页
九.SpringBoot集成Spring Cache 和 Red

九.SpringBoot集成Spring Cache 和 Red

作者: printf200 | 来源:发表于2019-05-12 11:49 被阅读0次

pom:

<?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 http://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.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>redisdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>redisdemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
            <version>RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

在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<Person>() {});
        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<Person>() {});
        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 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<Person>() {});
        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<Person>() {});
        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 和 Red

      本文链接:https://www.haomeiwen.com/subject/lmmagqtx.html