创建SpringBoot项目
在线创建方式
网址:https://start.spring.io/
然后创建Controller、Mapper、Service包
SpringBoot整合Redis
引入Redis依赖
org.springframework.boot
spring-boot-starter-data-redis
完整pom.xml
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.3.RELEASE
com.cyb
chenyb-mobile-redis
0.0.1-SNAPSHOT
chenyb-mobile-redis
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
io.projectreactor
reactor-test
test
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-maven-plugin
设置Redis的Template
RedisConfig.java
package com.cyb.mobile.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @ClassName:RedisConfig
* @Description:Redis配置类
* @Author:chenyb
* @Date:2020/8/16 11:48 下午
* @Versiion:1.0
*/
@Configuration //当前类为配置类
public class RedisConfig{
@Bean //redisTemplate注入到Spring容器
public RedisTemplate redisTemplate(RedisConnectionFactory factory){
RedisTemplate redisTemplate=new RedisTemplate<>();
RedisSerializer redisSerializer = new StringRedisSerializer();
redisTemplate.setConnectionFactory(factory);
//key序列化
redisTemplate.setKeySerializer(redisSerializer);
//value序列化
redisTemplate.setValueSerializer(redisSerializer);
//value hashmap序列化
redisTemplate.setHashKeySerializer(redisSerializer);
//key hashmap序列化
redisTemplate.setHashValueSerializer(redisSerializer);
return redisTemplate;
}
}
设置Redis连接信息
# 连接的那个数据库
spring.redis.database=0
# redis服务的ip地址
spring.redis.host=192.168.199.142
# redis端口号
spring.redis.port=6379
# redis的密码,没设置过密码,可为空
spring.redis.password=12345678
Redis工具类
redisTemplate API
opsForValue ==》String
opsForSet ==》Set
opsForHash ==》hash
opsForZset ==》SortSet
opsForList ==》list队列
RedisUtils.java
package com.cyb.mobile.utils;
import org.springframework.beans.