SpringBoot学习笔记6_整合Redis

Easter79
• 阅读 444

三十四  SpringBoot整合Redis(结合 SpringBoot整合Mybatis)

34.0 该案例是实现单机版Redis整合

34.1 相关依赖

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

 1           <dependency>
 2           <groupId>org.springframework.boot</groupId>
 3           <artifactId>spring-boot-starter-web</artifactId>  
 4        </dependency>
 5   
 6            <!-- mybatis(注解方式) -->
 7        <dependency>
 8                <groupId>org.mybatis.spring.boot</groupId>
 9                <artifactId>mybatis-spring-boot-starter</artifactId>
10                <version>1.3.1</version>
11        </dependency>
12        
13        <!-- Mysql -->
14        <dependency>
15                <groupId>mysql</groupId>
16                <artifactId>mysql-connector-java</artifactId>
17        </dependency>
18        
19        <!-- redis依赖 -->
20        <dependency>  
21             <groupId>org.springframework.boot</groupId>  
22             <artifactId>spring-boot-starter-data-redis</artifactId>  
23        </dependency>

相关依赖

34.2  mysql和redis的配置

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

 1 #数据库配置
 2 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 3 spring.datasource.username=root
 4 spring.datasource.password=
 5 spring.datasource.url=jdbc:mysql://localhost:3306/springboot
 6 
 7 #redis单服务器配置
 8 spring.redis.database=0
 9 spring.redis.host=127.0.0.1
10 spring.redis.port=6379
11 spring.redis.pool.max-active=8
12 spring.reids.pool.max-wait=-1
13 spring.redis.pool.max-idle=8
14 spring.redis.pool.min-idle=0
15 spring.redis.timeout=0
16

application.properties

34.3 开启缓存

在启动类上添加**@EnableCaching** 注解 

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

 1 package com.wu.app;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 import org.springframework.cache.annotation.EnableCaching;
 7 
 8 
 9 @SpringBootApplication(scanBasePackages={"com.wu.controller","com.wu.service"})
10 @MapperScan("com.wu.mapper")//需要单独扫描
11 @EnableCaching//开启缓存
12 public class SpringApplications {
13         //程序启动入口
14         public static void main(String []args){
15             SpringApplication.run(SpringApplications.class, args);
16         }
17 }

启动类

在需要缓存的service层方法中添加**@Cacheable** 注解

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

 1 package com.wu.service;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.cache.annotation.Cacheable;
 5 import org.springframework.stereotype.Service;
 6 
 7 import com.wu.mapper.UsersMapper;
 8 import com.wu.pojo.Users;
 9 @Service
10 public class UsersServiceImp implements UsersService {
11     @Autowired
12     private UsersMapper mapper;
13     
14     @Cacheable(value="user")//设置键值
15     @Override
16     public Users selectByName(String name) {
17         System.out.println("从数据库中查找");
18         return mapper.selectByName(name);
19     }
20     
21     
22 }

UsersServiceImp.java

实体类需要实现序列化接口 implements Serializable

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

 1 public class Users implements Serializable{
 2     private Integer id;
 3 
 4     private String name;
 5 
 6     private String password;
 7 
 8     private String email;
 9 
10     private Date birthday;
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name == null ? null : name.trim();
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password == null ? null : password.trim();
34     }
35 
36     public String getEmail() {
37         return email;
38     }
39 
40     public void setEmail(String email) {
41         this.email = email == null ? null : email.trim();
42     }
43 
44     public Date getBirthday() {
45         return birthday;
46     }
47 
48     public void setBirthday(Date birthday) {
49         this.birthday = birthday;
50     }

实体类

34.4 结果

这样第一次查询时即从数据库查询,再次查询即从缓存中加载 

三十五 SpringBoot整合Redis集群

35.0 搭建redis集群     参考文档

35.1 相关依赖(跟单机版一样)

35.2 相关配置

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

1 #数据库配置
2 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3 spring.datasource.username=root
4 spring.datasource.password=
5 spring.datasource.url=jdbc:mysql://localhost:3306/springboot
6 
7 #redis cluster配置
8 spring.redis.cluster.nodes=192.168.198.129:7001,192.168.198.129:7002,192.168.198.129:7003,192.168.198.129:7004,192.168.198.129:7005,192.168.198.129:7006
9

application.properties

35.3 编写Redis集群的配置类

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

 1 package com.wu.configure;
 2 
 3 import java.util.HashSet;
 4 import java.util.Set;
 5 import org.springframework.beans.factory.annotation.Value;
 6 import org.springframework.context.annotation.Bean;
 7 import org.springframework.context.annotation.Configuration;
 8 import redis.clients.jedis.HostAndPort;
 9 import redis.clients.jedis.JedisCluster;
10 
11 @Configuration
12 public class RedisClusterConfigrue {
13     @Value("${spring.redis.cluster.nodes}")
14     private String nodes;
15 
16     @Bean
17     public JedisCluster jedisCluster(){
18         //分割
19         String[] nodesArray = nodes.split(",");
20         Set<HostAndPort> hostAndPorts=new HashSet<>();
21         for (String node : nodesArray) {
22                 //分割
23                 String[] array = node.split(":");
24                 HostAndPort hostAndPort=new HostAndPort(array[0],Integer.parseInt(array[1]));
25                 hostAndPorts.add(hostAndPort);
26             }
27         JedisCluster jedisCluster=new JedisCluster(hostAndPorts);
28         return jedisCluster;
29         
30     }
31 }

RedisClusterConfigrue

35.4 简单测试

在service层的实现类中引入 

1 @Autowired
2 private JedisCluster JedisCluster;

添加如下方法

1 @Override
2     public String getRedisValue() {
3         JedisCluster.set("key","value");
4         return JedisCluster.get("key");
5     }

在controller层中调用该方法

1 @RequestMapping("/redis")
2     public String getRedisValue(){
3         return service.getRedisValue();
4     }

 三十六 使用RedisTemplate操作redis

参考:

36.1 相关依赖

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

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

spring-boot-starter-data-redis

36.2 相关配置

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

spring:
  datasource:
    username: root
    password: '123456'
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost/test
    type: com.alibaba.druid.pool.DruidDataSource
  redis:
    port: 6379
    jedis:
      pool:
        max-active: 50
        min-idle: 20
    host: 127.0.0.1
    database: 11

application.yml

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate redisTemplate=new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //Key的序列化
        StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        //value的序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper objectMapper =  new ObjectMapper();
        
        //定制 DateTime类型的序列化和反序列化
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(DateTime.class,new JodaDateTimeJsonSerializer());
        simpleModule.addDeserializer(DateTime.class,new JodaDateTimeJsonDeserializer());
        
        //设置类信息
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        
        //绑定simpleModule
        objectMapper.registerModule(simpleModule);

        //绑定objectMapper
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }
}

RedisConfig.java

如果需要序列化的实体类中使用了 joda 的 DateTime 类型的属性,(需要引入相关依赖

<dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.9.1</version>
    </dependency>

),对该类型的序列化话可以额外配置,如下:

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

public class JodaDateTimeJsonSerializer extends JsonSerializer<DateTime> {
    @Override
    public void serialize(DateTime dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(dateTime.toString("yyyy-MM-dd HH:mm:ss"));
    }
}

JodaDateTimeJsonSerializer.java

SpringBoot学习笔记6_整合Redis SpringBoot学习笔记6_整合Redis

public class JodaDateTimeJsonDeserializer extends JsonDeserializer<DateTime> {
    @Override
    public DateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        String dateString =jsonParser.readValueAs(String.class);
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

        return DateTime.parse(dateString,formatter);
    }
}

JodaDateTimeJsonDeserializer.java

然后引入到RedisConfig配置中

36.2.1 拓展

 RestTemplate 三种常用的序列化规则:具体参考 这里

序列化规则

说明

JdkSerializationRedisSerializer

默认序列化规则,要求对象必须实现 Serialable 接口

StringRedisSerializer

对象只能为 String

GenericJackson2JsonRedisSerializer

Java 与 JSON 的序列化与反序列化,好处是不需要对象实现 Serialable 接口,
但需要引入 jackson-databind 包

36.3 使用

36.3.1 引入

@Autowired
private RedisTemplate redisTemplate;

36.3.2 RedisTemplate Api总结

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解
Opencv中Mat矩阵相乘——点乘、dot、mul运算详解2016年09月02日00:00:36 \牧野(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fme.csdn.net%2Fdcrmg) 阅读数:59593
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
2年前
SpringBoot学习笔记6_整合Redis
三十四 SpringBoot整合Redis(结合SpringBoot整合Mybatis(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fwww.cnblogs.com%2Fwuba%2Fp%2F11232002.html))
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
2个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k