Springboot+redis 整合

运行环境:

JDK1.7.

SpringBoot1.4.7

redis3.0.4

1.生成Springboot项目,分别添加web,redis依赖,具体的maven依赖如下

 1      <dependency>
 2             <groupId>org.springframework.boot</groupId>
 3             <artifactId>spring-boot-starter-data-redis</artifactId>
 4         </dependency>
 5         <dependency>
 6             <groupId>org.springframework.boot</groupId>
 7             <artifactId>spring-boot-starter-web</artifactId>
 8         </dependency>
 9
10         <dependency>
11             <groupId>org.springframework.boot</groupId>
12             <artifactId>spring-boot-starter-test</artifactId>
13             <scope>test</scope>
14         </dependency>

数据源

使用spring的默认配置

在 src/main/resources/application.properties 中配置数据源信息。

 1 server.context-path=/redis
 2 server.port=9099
 3
 4 # REDIS (RedisProperties)
 5 # Redis数据库索引(默认为0)
 6 spring.redis.database=0
 7 # Redis服务器地址
 8 spring.redis.host=192.168.0.106
 9 # Redis服务器连接端口
10 spring.redis.port=6379
11 # Redis服务器连接密码(默认为空)
12 #Sspring.redis.password=
13 # 连接池最大连接数(使用负值表示没有限制)
14 spring.redis.pool.max-active=8
15 # 连接池最大阻塞等待时间(使用负值表示没有限制)
16 spring.redis.pool.max-wait=-1
17 # 连接池中的最大空闲连接
18 spring.redis.pool.max-idle=8
19 # 连接池中的最小空闲连接
20 spring.redis.pool.min-idle=0
21 # 连接超时时间(毫秒)
22 spring.redis.timeout=10

然后我们需要一个配置类,将配置文件与对象进行关联

新建一个RedisConfig类

@Configuration
@EnableAutoConfiguration
public class RedisConfig extends CachingConfigurerSupport {}

通过

p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 18.0px Consolas; color: #777777 }

@ConfigurationProperties

注解,将属性文件注入进来

@Bean
    @ConfigurationProperties(prefix = "spring.redis")
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        //System.out.println(config.getMaxWaitMillis());
        return config;
    }

这里需要注意的是,我们的属性文件并没有全部的注入进来,这里只是配置连接池的属性

我们还需要将redis的host,port等信息也注入进来

 1 @Autowired
 2     private Environment env;
 3
 4 @Bean
 5     @ConfigurationProperties(prefix = "spring.redis")
 6     public JedisConnectionFactory getConnectionFactory() {
 7         JedisConnectionFactory factory = new JedisConnectionFactory();
 8         JedisPoolConfig config = getRedisConfig();
 9         factory.setPoolConfig(config);
10         factory.setHostName(env.getProperty("spring.redis.host"));
11         factory.setPort(Integer.parseInt(env.getProperty("spring.redis.port").trim()));
12         factory.setDatabase(Integer.parseInt(env.getProperty("spring.redis.database").trim()));
13         logger.info("JedisConnectionFactory bean init success.");
14         return factory;
15     }

这样我们的属性信息就都配置好了

我们就要开始连接redis服务器,实现我们的业务了,这里我们先介绍下 RedisTemplate

spring 封装了 RedisTemplate 对象来进行对redis的各种操作,它支持所有的 redis 原生的 api。

RedisTemplate中定义了对5种数据结构操作

1 redisTemplate.opsForValue();//操作字符串
2 redisTemplate.opsForHash();//操作hash
3 redisTemplate.opsForList();//操作list
4 redisTemplate.opsForSet();//操作set
5 redisTemplate.opsForZSet();//操作有序set

StringRedisTemplate与RedisTemplate

  • 两者的关系是StringRedisTemplate继承RedisTemplate。
  • 两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。
  • SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。

    StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。

    RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。

我们先来写一个简单的例子,来看看RedisTemplate是怎么操作的

还是在RedisConfig类里面

1 @Bean
2     public RedisTemplate<String, ?> getRedisTemplate() {
3         RedisTemplate<String, ?> template = new RedisTemplate();
4         template.setConnectionFactory(getConnectionFactory());
5
6         return template;
7     }

然后我们新建一个service类,注入redisTemplate,操作相关的api,将键值对写入到redis服务器

 1 @Autowired
 2     private RedisTemplate<String, Object> redisTemplate; 6
 7     public void setKey(Map<String, Map<?, ?>> map) {
 8         ValueOperations<String, Object> opsForValue = redisTemplate.opsForValue();
 9         for (Map.Entry<String, Map<?, ?>> entry : map.entrySet()) {
10             String jsonStringFromMap = JsonUtils.getJsonStringFromMap(entry.getValue());
11             opsForValue.set(entry.getKey(), jsonStringFromMap);
12         }
13     }

再写一个controller类,注入service

@RequestMapping(value = "set")
    public ResponseVo setKey() {
        ResponseVo responseVo = new ResponseVo();
        try {
            Map<String, Map<?, ?>> map = new HashMap<String, Map<?, ?>>();
            Map<String, String> map2 = new HashMap<>();
            map2.put("value", "2");
            map.put("boxUid", map2);
            demoService.setKey(map);
            responseVo.setInfo("操作成功");
            responseVo.setData(map);
        } catch (Exception e) {
            responseVo.setInfo("操作失败");
            responseVo.setData(e.getMessage());
        }

        return responseVo;
    }

请求:http://localhost:9099/redis/demo/set

数据就写到redis数据库了。


序列化

RedisTemplate对象默认使用jdkSerializer实现序列化,如果想要更换序列化的实现方式,例如使用json实现value的序列化,可以进行如下配置

 1 @Bean
 2     Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer(ObjectMapper objectMapper) {
 3         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
 4                 Object.class);
 5         jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
 6         return jackson2JsonRedisSerializer;
 7     }
 8
 9     @Bean
10     RedisTemplate<String, Object> objRedisTemplate(JedisConnectionFactory connectionFactory,
11             Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer) {
12         RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
13         redisTemplate.setConnectionFactory(getConnectionFactory());
14         redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
15         StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
16         redisTemplate.setKeySerializer(stringRedisSerializer);
17         redisTemplate.setHashKeySerializer(stringRedisSerializer);
18         return redisTemplate;
19     }

redis的value将会以jason形式保存

对象序列化

除了String类型,实战中我们还经常会在Redis中存储对象,这时候我们就会想是否可以使用类似RedisTemplate<String, User>来初始化并进行操作。但是Spring Boot并不支持直接使用,需要我们自己实现RedisSerializer<T>接口来对传入对象进行序列化和反序列化,下面我们通过一个实例来完成对象的读写操作。

  • 创建要存储的对象:User
 1 public class User implements Serializable {
 2
 3     /**
 4      *
 5      */
 6     private static final long serialVersionUID = -8289770787953160443L;
 7
 8     private String username;
 9     private Integer age;
10
11     public User() {
12         super();
13         // TODO Auto-generated constructor stub
14     }
15
16     public User(String username, Integer age) {
17         this.username = username;
18         this.age = age;
19     }
20
21     public String getUsername() {
22         return username;
23     }
24
25     public void setUsername(String username) {
26         this.username = username;
27     }
28
29     public Integer getAge() {
30         return age;
31     }
32
33     public void setAge(Integer age) {
34         this.age = age;
35     }
36
37 }
  • 实现对象的序列化接口
 1 public class RedisObjectSerializer implements RedisSerializer<Object> {
 2     // private Converter<Object, byte[]> serializer = new SerializingConverter();
 3     // private Converter<byte[], Object> deserializer = new
 4     // DeserializingConverter();
 5     static final byte[] EMPTY_ARRAY = new byte[0];
 6
 7     @Override
 8     public Object deserialize(byte[] bytes) {
 9         if (isEmpty(bytes)) {
10             return null;
11         }
12         ObjectInputStream oii = null;
13         ByteArrayInputStream bis = null;
14         bis = new ByteArrayInputStream(bytes);
15         try {
16             oii = new ObjectInputStream(bis);
17             Object obj = oii.readObject();
18             return obj;
19         } catch (Exception e) {
20
21             e.printStackTrace();
22         }
23         return null;
24     }
25
26     @Override
27     public byte[] serialize(Object object) {
28         if (object == null) {
29             return EMPTY_ARRAY;
30         }
31         ObjectOutputStream obi = null;
32         ByteArrayOutputStream bai = null;
33         try {
34             bai = new ByteArrayOutputStream();
35             obi = new ObjectOutputStream(bai);
36             obi.writeObject(object);
37             byte[] byt = bai.toByteArray();
38             return byt;
39         } catch (IOException e) {
40             e.printStackTrace();
41         }
42         return null;
43     }
44
45     private boolean isEmpty(byte[] data) {
46         return (data == null || data.length == 0);
47     }
48 }
  • 配置针对User的RedisTemplate实例
@Bean
    public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, User> template = new RedisTemplate<String, User>();
        template.setConnectionFactory(getConnectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new RedisObjectSerializer());
        return template;
    }
  • 完成了配置工作后,编写测试用例实验效果
@Autowired
    private RedisTemplate<String, User> redisUserTemplate;

public void setUser(User user) {
        ValueOperations<String, User> opsForValue = redisUserTemplate.opsForValue();
        opsForValue.set(user.getUsername(), user);
        Integer age = opsForValue.get(user.getUsername()).getAge();
        String username = opsForValue.get(user.getUsername()).getUsername();
        System.out.println(age + " " + username);
    }

最后的结果是会输出年龄和姓名。

源代码

相关示例代码在redisBoot

时间: 2024-08-25 23:54:48

Springboot+redis 整合的相关文章

SpringBoot日记——Redis整合

上一篇文章,简单记录了一下缓存的使用方法,这篇文章将把我们熟悉的redis整合进来. 那么如何去整合呢?首先需要下载和安装,为了使用方便,也可以做环境变量的配置. 下载和安装的方法,之前有介绍,在docker中的使用,这里不做相关介绍,有想在windows环境下使用的,自己搜一下如何windows安装使用redis吧~(看这里也可以) 正题: SpringBoot对应(自带)RedisClient是不同的 SpringBoot1.5.x版本 -> jedis  SpringBoot2.x版本 -

SpringCloud+MyBatis+Redis整合—— 超详细实例(二)

2.SpringCloud+MyBatis+Redis redis是一种nosql数据库,以键值对<key,value>的形式存储数据,其速度相比于MySQL之类的数据库,相当于内存读写与硬盘读写的差别,所以常常用作缓存,用于少写多读的场景下,直接从缓存拿数据比从数据库(数据库要I/O操作)拿要快得多. 话不多说,接下来紧接上一章<SpringCloud+MyBatis+Redis整合-- 超详细实例(一)>搭建SpringCloud+MyBatis+Redis环境: 第一步:在p

springBoot+SpringData 整合入门

SpringData概述 SpringData :Spring的一个子项目.用于简化数据库访问,支持NoSQL和关系数据存储.其主要目标是使用数据库的访问变得方便快捷. SpringData 项目所支持NoSQL存储: MongoDB(文档数据库) Neo4j(图形数据库) Redis(键/值存储) Hbase(列族数据库) SpringData 项目所支持的关系数据存储技术: JDBC JPA Spring Data : 致力于减少数据访问层 (DAO) 的开发量. 开发者唯一要做的,就只是声

Springboot + redis + 注解 + 拦截器来实现接口幂等性校验

Springboot + redis + 注解 + 拦截器来实现接口幂等性校验 1. SpringBoot 整合篇 2. 手写一套迷你版HTTP服务器 3. 记住:永远不要在MySQL中使用UTF-8 4. Springboot启动原理解析 一.概念 幂等性, 通俗的说就是一个接口, 多次发起同一个请求, 必须保证操作只能执行一次比如: 订单接口, 不能多次创建订单 支付接口, 重复支付同一笔订单只能扣一次钱 支付宝回调接口, 可能会多次回调, 必须处理重复回调 普通表单提交接口, 因为网络超时

SpringBoot与整合其他技术

SpringBoot与整合其他技术 5.1 SpringBoot整合Mybatis 5.1.1 添加Mybatis的起步依赖 <!--mybatis起步依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</ver

Nginx+Lua+Redis整合实现高性能API接口 - 网站服务器 - LinuxTone | 运维专家网论坛 - 最棒的Linux运维与开源架构技术交流社区! - Powered by Discuz!

Nginx+Lua+Redis整合实现高性能API接口 - 网站服务器 - LinuxTone | 运维专家网论坛 - 最棒的Linux运维与开源架构技术交流社区! - Powered by Discuz! log.latermoon.com/

ssm+redis整合(通过cache方式)

这几天的研究ssm redis 终于进入主题了,今天参考了网上一些文章搭建了一下ssm+redis整合,特别记录下来以便以后可以查询使用,有什么不足请大牛们提点 项目架构 1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:/

ssm+redis整合(通过aop自定义注解方式)

此方案借助aop自定义注解来创建redis缓存机制. 1.创建自定义注解类 package com.tp.soft.common.util; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementTyp

SpringBoot Kafka 整合实例教程

1.使用IDEA新建工程引导方式,创建消息生产工程 springboot-kafka-producer. 工程POM文件代码如下: 1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instanc