专栏首页深入理解JavaSpring Boot整合Redis

Spring Boot整合Redis

Spring Boot整合Redis

一、Maven依赖

<?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>springboot.example</groupId>
    <artifactId>springboot-redis</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring-boot -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <!-- gson依赖 -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>

        <!-- 测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        
    </dependencies>
    
</project>

二、测试使用的实体类

本次测试一共设置了三个实体类,分别是User(用户)、Role(角色)、Department(部门)。三者之间的关系是:一个用户可以拥有多个角色,也就是用户和角色之间是一对多的关系,一个用户只属于一个部门,一个部门可以拥有多个用户,也就是说用户和部门之间是多对一的关系。

Department部门实体类:

package com.lemon.springboot.domain;

import java.io.Serializable;

/**
 * @author lemon
 */
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;
    }

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

Role角色实体类:

package com.lemon.springboot.domain;

import java.io.Serializable;

/**
 * @author lemon
 */
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;
    }

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

User用户实体类:

package com.lemon.springboot.domain;

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

/**
 * @author lemon
 */
public class User {

    private Long id;
    private String name;
    private Date createTime;
    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 getCreateTime(Date date) {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", createTime=" + createTime +
                ", department=" + department +
                ", roles=" + roles +
                '}';
    }
}

三、RedisConfig配置类(重要)

配置类主要是配置Redis连接的相关信息,也可以对RedisTemplate进行配置,针对项目进行相关配置。这里对RedisTemplate进行了JSON数据和字符串相关转换的配置。

RedisConfig配置类:

package com.lemon.springboot.configuration;

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;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author lemon
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(redisConnectionFactory);
        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);
        stringRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        stringRedisTemplate.afterPropertiesSet();
        return stringRedisTemplate;
    }

    /**
     * 配置RedisConnectionFactory
     *
     * @return RedisConnectionFactory实例对象
     */
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(8);
        jedisPoolConfig.setMinIdle(0);
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);
        jedisConnectionFactory.setHostName("192.168.25.133");
        jedisConnectionFactory.setPort(6379);
        return jedisConnectionFactory;
    }
}

四、测试类

package com.lemon.springboot.test;

import com.lemon.springboot.configuration.RedisConfig;
import com.lemon.springboot.domain.Department;
import com.lemon.springboot.domain.Role;
import com.lemon.springboot.domain.User;
import com.lemon.springboot.repository.UserRedis;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {RedisConfig.class, UserRedis.class})
public class RedisTest {

    private static Logger logger = LoggerFactory.getLogger(RedisTest.class);

    @Autowired
    private UserRedis userRedis;

    @Before
    public void init() {
        Department department = new Department();
        department.setName("开发部");

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

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

        User user = new User();
        user.setName("user");
        user.setCreateTime(new Date());
        user.setDepartment(department);
        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.notNull(user, "Redis数据库中未查到数据");
        logger.info("=====user===== name:{}, department:{}, role:{}", user.getName(), user.getDepartment().getName(), user.getRoles().get(0).getName());
    }
}

运行上面的测试方法,就可以对数据库进行操作了。代码托管在码云,可以下载

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Spring Boot+JPA+Mysql完成数据库整合操作

    Spring Boot结合JPA操作Mysql数据库十分方便,可以做到零配置文件。具体流程如下。

    itlemon
  • Spring Boot错误处理

    自定义一个类实现ErrorController,当系统发生404或者500错误的时候,就会自动进入到自定义的错误页面中,这要求在resources文件里面的te...

    itlemon
  • Spring Cloud微服务技术栈(五):客户端负载均衡Spring Cloud Ribbon部分源码分析

    为了使客户端具备负载均衡的能力,我们在代码中将RestTemplate交给Spring管理的时候,会加上@LoadBalanced注解,如下代码所示:

    itlemon
  • 【SpringBoot】Http请求统一异常(返回数据)处理与单元测试

    这个ResultUtil中的方法,其实写在BaseController中也挺不错的

    谙忆
  • Hibernate Annotation (Hibernate 注解)

    英文:http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/

    Hongten
  • Spring data 数据库建表(一对一,一对多,多对多)

    本文节选择电子书《Netkiller Java 手札》 DBA 如果你在不学习编程,你将失业。如今我们对DBA的依赖越来越少,多数框架都支持实体关系映射,通过面...

    netkiller old
  • SpringBoot开发案例之整合mongoDB

    JDK1.7、Maven、Eclipse、SpringBoot1.5.2、mongodb3.4,Robomongo(可视化工具)

    小柒2012
  • SpringBoot开发案例之整合mongoDB

    ? mongodb.jpg 开始前,建议大家去了解以下文章,当然不看也没问题: MongoDB从入门到“精通”之简介和如何安装 MongoDB从入门到“精通”...

    小柒2012
  • ServerForXML网络编程

    新建Dynamic Web Project,名称为ServerForXML(该勾选的勾上)。

    提莫队长
  • springboot+security 数据库中读取账号密码 使用security加密规则 实体类继承security的实体接口

    码云地址:https://gitee.com/huatao1994/springSecurity

    用户5899361

扫码关注云+社区

领取腾讯云代金券