4.0.0 org.springframework.boot spring-boot-starter-parent 2.2.6.RELEASE com.sin demo-springboot-redis 0.0.1-SNAPSHOT demo-springboot-redis Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 mysql mysql-connector-java org.mybatis.spring.boot mybatis-spring-boot-starter 2.2.2 tk.mybatis mapper-spring-boot-starter 2.1.5 org.projectlombok lombok org.springframework.boot spring-boot-starter-test test junit junit test org.yaml snakeyaml 1.23 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin
package com.sin;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** @author sin* @date 2022/11/25* @apiNote*/
@SpringBootApplication
public class SpringRedisMySQLRun {public static void main(String[] args) {SpringApplication.run(SpringRedisMySQLRun.class,args);System.out.println("===============启动成功================");}
}
## 配置端口
server:port: 80spring:## 配置数据库数据源datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/sindemousername: rootpassword: 123456redis:# 地址host: 192.168.11.128# 端口port: 6379# 密码password: 123456# 超时时间 5000毫秒timeout: 5000jedis: 连接池pool:# 连接池最小空闲连接min-idle: 0# 连接池的最大空闲连接max-idle: 8# 连接池最大阻塞等待时间(使用负数表示没有限制)max-wait: -1# 连接池最大连接数(使用负数表示没有限制)max-active: 8# mybatis配置
mybatis:# 获取配置文件的地址mapper-locations: classpath:/mybatis/mapper/*.xml# 获取实体类的地址type-aliases-package: com.sin.pojoconfiguration:# 开启驼峰命名map-underscore-to-camel-case: true
package com.sin.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @author sin* @date 2022/11/25* @apiNote*/
@RestController
public class TestController {@RequestMapping("/test")public String testControler(){System.out.println("测试成功");return "测试成功";}
}


## 启动redis
[root@My-Server redis]# cd /usr/local/redis/bin
[root@My-Server bin]# ./redis-server /usr/local/redis/etc/redis.conf
## 进入redis
[root@My-Server bin]# cd /usr/local/redis/bin
[root@My-Server bin]# ./redis-cli
## 密码登录
127.0.0.1:6379> auth 123456
OK
127.0.0.1:6379>

Spring封装了RedisTemplate来操作Redis,对redis底层开发包(Jedis,JRedis,RJC)进行了一个封装,在我们的RedisTemplate中定义了五种数据结构的操作方法,异常处理,序列化,发布订阅
package com.sin.controller;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;/*** @author sin* @date 2022/11/25* @apiNote*/
@RestController
public class RedisController {//注入RedisTemplate@Autowiredprivate RedisTemplate redisTemplate;//添加数据@PostMapping("/addData/key={key}/value={value}")//动态地址public Object addData(@PathVariable("key") String key,@PathVariable("value") String value){redisTemplate.opsForValue().set(key,value);System.out.println("数据添加成功"+redisTemplate);return "addData Success";}
}



//根据key获取value
@GetMapping("/getData/key={key}")
public Object getData(@PathVariable("key") String key){Object value = redisTemplate.opsForValue().get(key);System.out.println("数据为:"+value);return redisTemplate.opsForValue().get(key);
}


看到结果后是看不懂的,这个就跟它的序列化有关了。就是根据RedisTemplate将数据写入到redis中的时候会经过一个序列化操作,序列化操作后就变成了以上数据格式,这个并不影响程序,因为set写入时会有序列化操作,get获取数据时也就有着这么一个序列话操作,但是对于我们来说时很不友好的

在源码中我们能看到定义了各种数据类型的序列化的一个成员变量
if (defaultSerializer == null) { //当defaultSerializer为null//当为null时这里就会设定为JdkSerializationRedisSerializer,就会用jdk的序列化defaultSerializer = new JdkSerializationRedisSerializer( classLoader != null ? classLoader : this.getClass().getClassLoader());
}
if (keySerializer == null) {//当keySerializer为null时,//这里就直接把defaultSerializer给keySerializerkeySerializer = defaultSerializer;defaultUsed = true;
}
我们没有定义,它就用的jdk的序列化将数据传输过来的
package com.sin.conf;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.Jackson2JsonRedisSerializer;/*** @author sin* @date 2022/11/25* @apiNote*/
@Configuration //表示该类为配置类
public class RedisConfig {@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory){//实例化RedisTemplateRedisTemplate redisTemplate = new RedisTemplate<>();//设置连接工厂redisTemplate.setConnectionFactory(connectionFactory);//指定k,v的序列化方式(json)Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);//默认序列化为json格式redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);return redisTemplate;}
}
Json序列化

package com.sin.conf;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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @author sin* @date 2022/11/25* @apiNote*/
@Configuration //表示该类为配置类
public class RedisConfig {@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory){//实例化RedisTemplateRedisTemplate redisTemplate = new RedisTemplate<>();//设置连接工厂redisTemplate.setConnectionFactory(connectionFactory);//指定k,v的序列化方式(json)Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);// //默认序列化为json格式
// redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);//key设置为String类型redisTemplate.setKeySerializer(new StringRedisSerializer());//value设置为Json格式redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);return redisTemplate;}
}
key为String格式,value为Json格式

package com.sin.demo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** redis配置类**/
@EnableCaching
@Configuration//标记该类为配置类,
public class RedisConfig {/*** 对读写的数据进行序列化操作* @param factory 连接工厂,* @return*/@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory factory){//实例化redisTemplateRedisTemplate redisTemplate = new RedisTemplate<>();//设置连接工厂redisTemplate.setConnectionFactory(factory);Jackson2JsonRedisSerializer
package com.sin.demo.util;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import sun.security.ec.point.ProjectivePoint;import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** redisTemplate封装*/
@Component
public class RedisUtil {@Autowiredprivate RedisTemplate redisTemplate;public RedisUtil(RedisTemplate redisTemplate) {this.redisTemplate = redisTemplate;}/*** 指定缓存失效时间* @param key* @param time* @return*/public boolean expire(String key,long time){try {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;}catch (Exception e){e.printStackTrace();return false;}}/*** 指定key过期时间* @param key* @return*/public long getExpire(String key){return redisTemplate.getExpire(key,TimeUnit.SECONDS);}/*** 判断key是否存在* @param key* @return*/public boolean hasKey(String key){try {return redisTemplate.hasKey(key);}catch (Exception e){e.printStackTrace();return false;}}/*** 删除缓存* @param key*/@SuppressWarnings("unchecked")public void del(String ... key){if(key!=null&&key.length>0){if(key.length==1){redisTemplate.delete(key[0]);}else {redisTemplate.delete((Collection) CollectionUtils.arrayToList(key));}}}//=====================================================Redis的String数据类型操作=========================================/*** 普通缓存的获取* @param key* @return*/public Object get(String key){return key==null?null:redisTemplate.opsForValue().get(key);}/*** 普通缓存的存放* @param key* @param value* @return*/public boolean set(String key,Object value){try{redisTemplate.opsForValue().set(key,value);return true;}catch (Exception e){e.printStackTrace();return false;}}/*** 普通缓存放入并设置时间* @param key* @param value* @param time* @return*/public boolean set(String key,Object value,long time){try{if(time>0){redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);}else {set(key,value);}return true;}catch (Exception e){e.printStackTrace();return false;}}/*** 递增* @param key* @param delta* @return*/public long incr(String key,long delta){if (delta<0){throw new RuntimeException("递增的条件必须大于0");}return redisTemplate.opsForValue().increment(key,delta);}/*** 递减* @param key* @param delta* @return*/public long decr(String key,long delta){if (delta<0){throw new RuntimeException("递减的条件不许大于0");}return redisTemplate.opsForValue().decrement(key,-delta);}//===============================================redis的Hash数据类型操作====================================================/*** Hashget* @param key 不能为null* @param itme 不能为null* @return*/public Object hget(String key,String itme ){return redisTemplate.opsForHash().get(key,itme);}/*** 获取hashkey对应的所有键值* @param key* @return*/public Map
public class Student {private Integer id;private String name ;private Integer age;private String dept;//班级set,get方法}
package com.sin.controller;import com.sin.pojo.Student;
import com.sin.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;/*** @author sin* @date 2022/11/25* @apiNote*/
@RestController
public class RedisController {//注入RedisTemplate@Autowiredprivate RedisTemplate redisTemplate;@Autowiredprivate RedisUtil redisUtil;//添加数据@PostMapping("/addData/key={key}/value={value}")//动态地址public Object addData(@PathVariable("key") String key,@PathVariable("value") String value){redisTemplate.opsForValue().set(key,value);System.out.println("数据添加成功"+redisTemplate);return "addData Success";}//根据key获取value@GetMapping("/getData/key={key}")public Object getData(@PathVariable("key") String key){Object value = redisTemplate.opsForValue().get(key);System.out.println("数据为:"+value);return redisTemplate.opsForValue().get(key);}/*** 添加list对象数据到redis中* @return*/@RequestMapping(value = "/setList")public boolean setList(){List stuList = new ArrayList<>();Student student = new Student();student.setId(1);student.setAge(23);student.setDept("saas");student.setName("张三");Student student1 = new Student();student1.setId(2);student1.setAge(22);student1.setDept("微服务");student1.setName("李四");Student student2 = new Student();student2.setId(3);student2.setAge(23);student2.setDept("saas");student2.setName("王五");Student student3 = new Student();student3.setId(4);student3.setAge(24);student3.setDept("微服务");student3.setName("赵六");stuList.add(student);stuList.add(student1);stuList.add(student2);stuList.add(student3);return redisUtil.lSetList("student",stuList);}/*** 获取全部数据* @return*/@RequestMapping(value = "getList")public Object getList(){return redisUtil.lGet("student",0,-1);}}


SpringBoot+SpringMVC+redis+mysql来实现项目中的crud操作,redis做缓存数据库,针对频繁需要查询或者解决单点问题都会把数据库到redis来分配服务器压力。
create table demo_user(id int(10) auto_increment primary key not null ,user_name varchar(40) not null ,password varchar(10) not null ,sex int(10) not null );alter table demo_user charset = utf8;alter table demo_user convert to character set utf8;
public class DemoUser implements Serializable {private long id;private String userName;private String password;private long sex;// setter getter方法
}
package com.sin.mapper;import com.sin.pojo.DemoUser;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;import java.util.List;/*** dao层*/
@Repository
@Mapper
public interface DemoUserMapper {//用户列表@Select("select * from demo_user")@Results({@Result(property = "userName",column = "user_name"),@Result(property = "password",column = "password")})List queryAll();//根据id获取demo_user@Select("select * from demo_user where id = #{id}")@Results({@Result(property = "userName",column = "user_name"),@Result(property = "password",column = "password")})DemoUser findUserById(int id);@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")@Insert("insert into demo_user(id,user_name,password,sex)values" +"(#{id},#{userName},#{password},#{sex})")int add(DemoUser user);@Select("select * from demo_user where user_name = #{userName} ")@Results({@Result(property = "userName",column = "user_name"),@Result(property = "password",column = "password")})DemoUser findUserByName(String userName);//根据id修改demoUser@Update("update demo_user set user_name=#{userName},password=#{password}," +"sex=#{sex} where id=#{id}")int updateUser(DemoUser demoUser);//删除用户@Delete("delete from demo_user where id = #{id}")int deleteUserById(int id);}
package com.sin.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisInvalidSubscriptionException;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;/*** redis 配置类* 配置redisTemplate序列化*/
public class RedisConfig extends CachingConfigurerSupport {/*** 选择redis作为默认缓存工具**/@Beanpublic CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory){//设置缓存时间为一个小时RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1));return RedisCacheManager.builder(RedisCacheWriter.lockingRedisCacheWriter(redisConnectionFactory)).cacheDefaults(redisCacheConfiguration).build();}/*** 配置redisTemplate相关配置**/@Beanpublic RedisTemplate redisTemplate(RedisConnectionFactory factory){RedisTemplate redisTemplate = new RedisTemplate<>();//配置连接工厂redisTemplate.setConnectionFactory(factory);//使用Jackson2JsonRedisSerializer来序列化何反序列化redis的value值Jackson2JsonRedisSerializer jsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper objectMapper = new ObjectMapper();//指定要序列化的域,field,get和set,以及修饰符范围,ANY都是有private和publicobjectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);//指定序列化输入的类型,类必须时非final修饰的,objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jsonRedisSerializer.setObjectMapper(objectMapper);//值采用json序列化redisTemplate.setValueSerializer(jsonRedisSerializer);//使用StringRedisSerrializer来序列化和反序列化redis的key值redisTemplate.setKeySerializer(new StringRedisSerializer());//设置hash key 和value序列化模式redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(jsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}/** 对hash类型的数据操作*/@Beanpublic HashOperations hashOperations(RedisTemplate redisTemplate){return redisTemplate.opsForHash();}/*** 对redis 字符串String类型数据操作*/@Beanpublic ValueOperations valueOperations(RedisTemplate redisTemplate){return redisTemplate.opsForValue();}/*** 对redis 链表list类型数据操作*/@Beanpublic ListOperationslistOperations(RedisTemplate redisTemplate){return redisTemplate.opsForList();}/*** 对redis 无序集合set类型数据操作*/@Beanpublic SetOperations setOperations(RedisTemplate redisTemplate){return redisTemplate.opsForSet();}/*** 对redis 有序结合zset类型数据操作*/@Beanpublic ZSetOperations zSetOperations(RedisTemplate redisTemplate){return redisTemplate.opsForZSet();}}
public interface DemoUserService {//查询全部List queryAll();//根据id查询DemoUser findUserById(int id);//根据id进行修改int updateUser(DemoUser demoUser);//根据id进行删除int deleteUserById(int id);//添加数据int addUser(DemoUser user);
}
package com.sin.service.impl;import com.sin.mapper.DemoUserMapper;
import com.sin.pojo.DemoUser;
import com.sin.service.DemoUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.concurrent.TimeUnit;@Service
public class DemoUserServiceImpl implements DemoUserService {@Autowiredprivate DemoUserMapper demoUserMapper;@Autowiredprivate RedisTemplate redisTemplate;//查询全部操作@Overridepublic List queryAll() {return demoUserMapper.queryAll();}/*** 根据id进行查询* 获取用户策略,先从缓存中获取用户,没有则读取mysql数据,再将读取的数据写入缓存中*/@Overridepublic DemoUser findUserById(int id) {String key = "user_" + id;ValueOperations operations = redisTemplate.opsForValue();//判断redis中是否有键为key的缓存boolean haskey = redisTemplate.hasKey(key);if (haskey){DemoUser user = operations.get(key);System.out.println("从缓存中获取的数据:"+user.getUserName());System.out.println("----------------------------------");return user;}else {DemoUser user = demoUserMapper.findUserById(id);System.out.println("查询数据库中的数据"+ user.getUserName());System.out.println("--------------------写入数据------------------");//写入数据operations.set(key,user,5, TimeUnit.HOURS);return user;}}/*** 更新用户* 先更新数据库,成功之后,删除原来的缓存,再更新缓存* @param demoUser* @return*/@Overridepublic int updateUser(DemoUser demoUser) {ValueOperations operations = redisTemplate.opsForValue();int result = demoUserMapper.updateUser(demoUser);if (result!=0){String key = "user_"+demoUser.getId();boolean haskey = redisTemplate.hasKey(key);if (haskey){redisTemplate.delete(key);System.out.println("删除缓存中的key----"+key);}//将更新后的数据加入缓存中DemoUser demoUserNew = demoUserMapper.findUserById((int) demoUser.getId());if (demoUserNew != null){operations.set(key,demoUserNew,3,TimeUnit.HOURS);}}return result;}/*** 根据id删除* 删除数据表中的数据,然后删除缓存* @param id* @return*/@Overridepublic int deleteUserById(int id) {int result = demoUserMapper.deleteUserById(id);String key = "user_" + id;if (result != 0){boolean haskey = redisTemplate.hasKey(key);if (haskey){redisTemplate.delete(key);System.out.println("删除了缓存中的key"+ key);}}return result;}@Overridepublic int addUser(DemoUser user) {DemoUser user1 = demoUserMapper.findUserByName(user.getUserName());int result;if (user1 != null){result = 0;return result;}else{ValueOperations operations = redisTemplate.opsForValue();result = demoUserMapper.add(user);if (result != 0 ){String key = "user_" +user.getId();boolean haskey = redisTemplate.hasKey(key);if(haskey){redisTemplate.delete(key);}if (user != null){operations.set(key,user,3,TimeUnit.HOURS);}}return result;}}
}
package com.sin.controller;import com.sin.pojo.DemoUser;
import com.sin.service.DemoUserService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@RestController
public class DemoUserController {@Autowiredprivate DemoUserService demoUserService;@RequestMapping("/queryAll")public List queryAll(){List list = demoUserService.queryAll();return list;}@RequestMapping("/addUser")public String addUser(){DemoUser user = new DemoUser();user.setUserName("李四");user.setPassword("12112");user.setSex(1);user.setBirthday( new Date());int resutl= demoUserService.addUser(user);if (resutl != 0){return "add DemoUser success";}return "add demouser fail";}@RequestMapping("/findUserById")public Map findUserById(@RequestParam int id){DemoUser user = demoUserService.findUserById(id);Map result = new HashMap<>();result.put("id",user.getId());result.put("username",user.getUserName());result.put("pwd",user.getPassword());result.put("sex",user.getSex());result.put("birthday",user.getBirthday());return result;}@RequestMapping("/updateUser")public String updateUser(){DemoUser user = new DemoUser();user.setId(1);user.setUserName("张三");user.setPassword("123456");user.setSex(18);user.setBirthday((Timestamp) new Date());int result = demoUserService.updateUser(user);if (result != 0){return "update user success";}return "fall";}@RequestMapping("/deleteUserById")public String deleteUserById(@RequestParam int id){int result = demoUserService.deleteUserById(id);if (result != 0){return "delete Success";}return "delete fall";}}

上一篇:古代关于月亮的诗句
下一篇:第三个字是观字的成语