三十四 SpringBoot整合Redis(结合 SpringBoot整合Mybatis)
34.0 该案例是实现单机版Redis整合
34.1 相关依赖
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的配置
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** 注解
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** 注解
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
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 相关配置
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集群的配置类
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 相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring-boot-starter-data-redis
36.2 相关配置
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
@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>
),对该类型的序列化话可以额外配置,如下:
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
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;