吴裕雄天生自然Spring BootSpring Boot整合Redis

1.Spring Data Redis
Spring对Redis的支持是通过Spring Data Redis来实现的。Spring Data Redis为我们提供了RedisTemplate和StringRedisTemplate两个模板来进行数据操作,其中,StringRedisTemplate只针对键值都是字符串类型的数据进行操作。
2.Serializer
    当数据存储到Redis时,键和值都是通过Spring提供的Serializer序列化到数据的。RedisTemplate默认使用JdkSerializationRedisSerializer序列化的,StringRedisTemplate默认使用StringRedisSerializer序列化的。
在RedisAutoConfiguration配置类中,为我们默认配置了RedisTemplate和StringRedisTemplate,让我们可以直接使用Redis存储数据。
    在RedisProperties类中,我们看到可以使用以“spring.redis”为前缀的属性在application.properties中配置Redis,主要属性默认配置如下:
    spring.redis.database = 0 #数据库名db0
    spring.redis.host = localhost #服务器地址
    spring.redis.port = 6379 #连接端口号
    从上述默认属性值可以看出,默认为我们配置了数据库名为db0、服务器地址为localhost、端口号为6379的Redis。
    因此,在Spring Boot应用中,我们只要引入spring-boot-starter-data-redis依赖就可以使用默认配置的Redis进行数据操作。
在Spring Boot应用中使用StringRedisTemplate和RedisTemplate模板访问操作Redis数据库。
1.创建基于spring-boot-starter-data-redis依赖的Spring Boot Web应用ch6_9
2.配置application.properties文件
3.创建实体类
4.创建数据访问层
5.创建控制器层
6.修改配置类Ch69Application
7.运行测试
<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>
    <groupId>com.redis</groupId>
    <artifactId>SringBoot-Redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <!-- 声明项目配置依赖编码格式为 utf-8 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <fastjson.version>1.2.24</fastjson.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.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
package com.ch.ch6_9.entity;

import java.io.Serializable;

public class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    private String sno;
    private String sname;
    private Integer sage;

    public Student() {
        super();
    }

    public Student(String sno, String sname, Integer sage) {
        super();
        this.sno = sno;
        this.sname = sname;
        this.sage = sage;
    }

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getSage() {
        return sage;
    }

    public void setSage(Integer sage) {
        this.sage = sage;
    }
}
package com.ch.ch6_9.repository;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
import com.ch.ch6_9.entity.Student;

@Repository
public class StudentRepository {
    @SuppressWarnings("unused")
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @SuppressWarnings("unused")
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    /**
     * 使用@Resource注解指定stringRedisTemplate,可注入基于字符串的简单属性操作方法 ValueOperations<String,
     * String> valueOpsStr = stringRedisTemplate.opsForValue();
     */
    @Resource(name = "stringRedisTemplate")
    ValueOperations<String, String> valueOpsStr;
    /**
     * 使用@Resource注解指定redisTemplate,可注入基于对象的简单属性操作方法 ValueOperations<Object, Object>
     * valueOpsObject = redisTemplate.opsForValue();
     */
    @Resource(name = "redisTemplate")
    ValueOperations<Object, Object> valueOpsObject;

    /**
     * 保存字符串到redis
     */
    public void saveString(String key, String value) {
        valueOpsStr.set(key, value);
    }

    /**
     * 保存对象到redis
     */
    public void saveStudent(Student stu) {
        valueOpsObject.set(stu.getSno(), stu);
    }

    /**
     * 保存List数据到redis
     */
    public void saveMultiStudents(Object key, List<Student> stus) {
        valueOpsObject.set(key, stus);
    }

    /**
     * 从redis中获得字符串数据
     */
    public String getString(String key) {
        return valueOpsStr.get(key);
    }

    /**
     * 从redis中获得对象数据
     */
    public Object getObject(Object key) {
        return valueOpsObject.get(key);
    }
}
package com.ch.ch6_9.controller;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ch.ch6_9.entity.Student;
import com.ch.ch6_9.repository.StudentRepository;

@RestController
public class TestRedisController {
    @Autowired
    private StudentRepository studentRepository;

    @RequestMapping("/save")
    public void save() {
        studentRepository.saveString("uname", "陈恒");
        Student s1 = new Student("111", "陈恒1", 77);
        studentRepository.saveStudent(s1);
        Student s2 = new Student("222", "陈恒2", 88);
        Student s3 = new Student("333", "陈恒3", 99);
        List<Student> stus = new ArrayList<Student>();
        stus.add(s2);
        stus.add(s3);
        studentRepository.saveMultiStudents("mutilStus", stus);
    }

    @RequestMapping("/getUname")
    @Cacheable(value = "myuname")
    public String getUname(String key) {
        System.out.println("测试缓存");
        return studentRepository.getString(key);
    }

    @RequestMapping("/getStudent")
    public Student getStudent(String key) {
        return (Student) studentRepository.getObject(key);
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getMultiStus")
    public List<Student> getMultiStus(String key) {
        return (List<Student>) studentRepository.getObject(key);
    }
}
package com.ch.ch6_9;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
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;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@EnableCaching
@SpringBootApplication
public class Ch69Application {
    public static void main(String[] args) {
        SpringApplication.run(Ch69Application.class, args);
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> rTemplate = new RedisTemplate<Object, Object>();
        rTemplate.setConnectionFactory(redisConnectionFactory);
        @SuppressWarnings({ "unchecked", "rawtypes" })
        Jackson2JsonRedisSerializer<Object> 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);
        // 设置值的序列化采用Jackson2JsonRedisSerializer
        rTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置键的序列化采用StringRedisSerializer
        rTemplate.setKeySerializer(new StringRedisSerializer());
        return rTemplate;
    }
}

 

 

 

原文地址:https://www.cnblogs.com/tszr/p/15374773.html