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>

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

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

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

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

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

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

}

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

此时再打开桌面客户端

时间: 2024-10-04 10:40:52

Spring Boot + Redis的相关文章

spring boot + redis 实现session共享

这次带来的是spring boot + redis 实现session共享的教程. 在spring boot的文档中,告诉我们添加@EnableRedisHttpSession来开启spring session支持,配置如下: @Configuration @EnableRedisHttpSession public class RedisSessionConfig { } 而@EnableRedisHttpSession这个注解是由spring-session-data-redis提供的,所以

spring boot redis 缓存(cache)集成

Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 spring boot 连接Mysql spring boot配置druid连接池连接mysql spring boot集成mybatis(1) spring boot集成mybatis(2) – 使用pagehelper实现分页 spring boot集成mybatis(3) – mybatis ge

spring boot redis分布式锁

随着现在分布式架构越来越盛行,在很多场景下需要使用到分布式锁.分布式锁的实现有很多种,比如基于数据库. zookeeper 等,本文主要介绍使用 Redis 做分布式锁的方式,并封装成spring boot starter,方便使用 一. Redis 分布式锁的实现以及存在的问题 锁是针对某个资源,保证其访问的互斥性,在实际使用当中,这个资源一般是一个字符串.使用 Redis 实现锁,主要是将资源放到 Redis 当中,利用其原子性,当其他线程访问时,如果 Redis 中已经存在这个资源,就不允

从.Net到Java学习第四篇——spring boot+redis

从.Net到Java学习第一篇——开篇 从.Net到Java学习第二篇——IDEA and start spring boot 从.Net到Java学习第三篇——spring boot+mybatis+mysql 接上一篇,本篇使用到的框架redis.FastJSON. 环境准备 安装redis,下图是我本机的redis绿色版,你可以网上自行下载安装,如果不知道如何怎么操作,可以移步到我的另一篇文章:ASP.NET Redis 开发 以管理员身份打开CMD窗口: C:\Users\zouqj>e

Spring boot redis自增编号控制 踩坑

近段期间,公司 接手一个订单号生成服务,规则的话已经由项目经理他们规定好了,主要是后面的四位数代表的关于当前订单号已经执行第几个了.而这里面有一个要求就是支持分布式.为了实现这个东西,刚开始我使用了redis的incr来解决这个问题,因为我们后端开发用的是Spring boot,所以我网上找了一个代码如下: 1 /** 2 * 3 * @param key 4 * @param liveTime 5 * @return 6 */ 7 public Long incr(String key, lo

java版spring cloud+spring boot+redis社交电子商务平台(十)使用Swagger2构建强大的RESTful API文档(2)

添加文档内容在完成了上述配置后,其实已经可以生产文档内容,但是这样的文档主要针对请求本身,而描述主要来源于函数等命名产生,对用户并不友好,我们通常需要自己增加一些说明来丰富文档内容.如下所示,我们通过@ApiOperation注解来给API增加说明.通过@ApiImplicitParams.@ApiImplicitParam注解来给参数增加说明. @RestController @RequestMapping(value="/users") // 通过这里配置使下面的映射都在/user

java版spring cloud+spring boot+redis多租户社交电子商务平台(七)开发Web应用(1)

静态资源访问在我们开发Web应用的时候,需要引用大量的js.css.图片等静态资源. 默认配置Spring Boot默认提供静态资源目录位置需置于classpath下,目录名需符合如下规则: /static/public/resources/META-INF/resources举例:我们可以在src/main/resources/目录下创建static,在该位置放置一个图片文件.启动程序后,尝试访问http://localhost:8080/D.jpg.如能显示图片,配置成功. 渲染Web页面在

java版spring cloud+spring boot+redis社交电子商务平台-Spring Cloud Config服务器

服务器为外部配置(名称值对或等效的YAML内容)提供了基于资源的HTTP.服务器可以使用@EnableConfigServer注释轻松嵌入到Spring Boot应用程序中.所以这个应用程序是一个配置服务器: ConfigServer.java @SpringBootApplication @EnableConfigServer public class ConfigServer { public static void main(String[] args) { SpringApplicati

java版spring cloud+spring boot+redis社交电子商务平台-docker-feign配置(五)

简介 B2B2C电子商务平台源码请加企鹅求求:一零三八七七四六二六.上一节我们讨论了怎么用feign声明式调用cloud的生产者,这节我们讨论一下feign配置,通过编写配置类,我们可以自定义feign的日志级别,日志扫描目录,可以通过feign调用服务在eureka上的调用信息. feign声明接口之后,在代码中通过@Resource或者@Autowired注入之后即可使用. @FeignClient标签的常用属性如下: name:指定FeignClient的名称,如果项目使用了Ribbon,