Spring Boot + Redis

Posted uptothesky

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot + Redis相关的知识,希望对你有一定的参考价值。

启动redis

docker run --name redisServer -P -d  redis

redis自带客户端,启动客户端

docker run -it --link redisServer:db --entrypoint redis-cli redis -h db

也可以使用桌面工具Redis Desktop Manager测试

下载地址:https://redisdesktop.com/download

下载完后安装,打开程序

 

连接服务器

可以看到上面存进去的name

 

新建一个Spring Boot项目,pom.xml如下

<?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>

    <groupId>org.mythsky</groupId>
    <artifactId>spring-boot-redis-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-redis-demo</name>
    <description>Demo project for Spring Boot</description>

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

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.2.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
            <version>2.9.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

        <!--<dependency>-->
            <!--<groupId>springboot.db</groupId>-->
            <!--<artifactId>mysql</artifactId>-->
            <!--<version>${project.version}</version>-->
        <!--</dependency>-->
    </dependencies>

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


</project>
View Code

添加User

package org.mythsky.springbootredisdemo.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable {
    private Long id;
    private String name;
    private Date createDate;
    private Department department;
    private List<Role> roles;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }
}
View Code

Department

package org.mythsky.springbootredisdemo.domain;

import java.io.Serializable;

public class Department implements Serializable {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

Role

package org.mythsky.springbootredisdemo.domain;

import java.io.Serializable;

public class Role implements Serializable {
    private Long id;
    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

RedisConfig

package org.mythsky.springbootredisdemo.config;

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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

@Configuration
public class RedisConfig {
    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        JedisConnectionFactory redisConnectionFactory=new JedisConnectionFactory();
        redisConnectionFactory.setHostName("192.168.31.146");
        redisConnectionFactory.setPort(32769);
        redisConnectionFactory.setUsePool(true);
        return redisConnectionFactory;
    }
    @Bean
    public RedisTemplate<String,String> redisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate template=new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper=new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
View Code

UserRedis

package org.mythsky.springbootredisdemo.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.mythsky.springbootredisdemo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

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

@Repository
public class UserRedis {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void add(String key,Long time,User user){
        Gson gson=new Gson();
        redisTemplate.opsForValue().set(key,gson.toJson(user),time, TimeUnit.MINUTES);
    }

    public void add(String key, Long time, List<User> users){
        Gson gson=new Gson();
        redisTemplate.opsForValue().set(key,gson.toJson(users),time, TimeUnit.MINUTES);
    }

    public User get(String key){
        Gson gson=new Gson();
        User user=null;
        String userJson=redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(userJson)){
            user=gson.fromJson(userJson,User.class);
        }
        return user;
    }

    public List<User> getList(String key){
        Gson gson=new Gson();
        List<User> users=null;
        String listJson=redisTemplate.opsForValue().get(key);
        if(!StringUtils.isEmpty(listJson)){
            users=gson.fromJson(listJson,new TypeToken<List<User>>(){}.getType());
        }
        return users;
    }

    public void delete(String key){
        redisTemplate.opsForValue().getOperations().delete(key);
    }
}
View Code

SpringBootRedisDemoApplicationTests

package org.mythsky.springbootredisdemo;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mythsky.springbootredisdemo.config.RedisConfig;
import org.mythsky.springbootredisdemo.domain.Department;
import org.mythsky.springbootredisdemo.domain.Role;
import org.mythsky.springbootredisdemo.domain.User;
import org.mythsky.springbootredisdemo.service.UserRedis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

    private static Logger logger= LoggerFactory.getLogger(SpringBootRedisDemoApplicationTests.class);
    @Autowired
    UserRedis userRedis;
    @Before
    public void setup(){
        Department department=new Department();
        department.setName("开发部");

        Role role=new Role();
        role.setName("admin");

        User user=new User();
        user.setName("user");
        user.setCreateDate(new Date());
        user.setDepartment(department);

        List<Role> roles=new ArrayList<Role>();
        roles.add(role);

        user.setRoles(roles);

        userRedis.delete(this.getClass().getName()+":userByName:"+user.getName());
        userRedis.add(this.getClass().getName()+":userByName:"+user.getName(),10l,user);
    }
    @Test
    public void get() {
        User user=userRedis.get(this.getClass().getName()+":userByName:user");
        Assert.assertNotNull(user);
        logger.info("======user====== name:{}, department:{}, role:{}",user.getName(),user.getDepartment(),user.getRoles().get(0).getName());
    }

}
View Code

运行,可以在测试窗口看到结果

 

 此时再打开桌面客户端

 

 

连接redis集群

官方文档:

最主要的是设置RedisConnectionFactory

pom

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

config

@Component
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class ClusterConfigurationProperties {

    /*
     * spring.redis.cluster.nodes[0] = 127.0.0.1:7379
     * spring.redis.cluster.nodes[1] = 127.0.0.1:7380
     * ...
     */
    List<String> nodes;

    /**
     * Get initial collection of known cluster nodes in format {@code host:port}.
     *
     * @return
     */
    public List<String> getNodes() {
        return nodes;
    }

    public void setNodes(List<String> nodes) {
        this.nodes = nodes;
    }
}
View Code
@Configuration
public class AppConfig {

    /**
     * Type safe representation of application.properties
     */
    @Autowired
    ClusterConfigurationProperties clusterProperties;
    @Value("${spring.redis.password}")
    private String password;

    public @Bean
    RedisConnectionFactory connectionFactory() {
        RedisClusterConfiguration configuration=new RedisClusterConfiguration(clusterProperties.getNodes());
        configuration.setPassword(RedisPassword.of(password));
        return new JedisConnectionFactory(configuration);
    }
}
View Code

配置文件

spring.redis.cluster.nodes=172.20.102.65:7001,172.20.102.65:7002,172.20.102.65:7003,172.20.102.66:7004,172.20.102.66:7005,172.20.102.66:7006
spring.redis.password=123456

 

测试

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

    @Test
    public void contextLoads() {
        String result= stringRedisTemplate.opsForValue().get("api:tmp:users:1375bf2a-8e03-4097-8e1f-803787b6fac2");
        System.out.println(result);
    }
    @Test
    public void test1(){
        String result=redisTemplate.opsForValue().get("api:tmp:users:1375bf2a-8e03-4097-8e1f-803787b6fac2");
        System.out.println(result);
    }
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
}
View Code

 

以上是关于Spring Boot + Redis的主要内容,如果未能解决你的问题,请参考以下文章

解决spring-boot启动中碰到的问题:Cannot determine embedded database driver class for database type NONE(转)(代码片段

Spring Boot 整合Redis 实现缓存

spring boot + redis 实现session共享

spring boot项目之redis缓存

spring boot + redis 实现session共享

一张图,理顺 Spring Boot应用在启动阶段执行代码的几种方式