乐淘资源 干货福利 立即可用的实战源码(springboot+redis+mybatis+restTemplate)

立即可用的实战源码(springboot+redis+mybatis+restTemplate)

广告位

关于这个demo工程

开发springboot应用的时候,经常用到redis、mybatis、restTemplate这些技术,在此将常用代码和配置都整理出来,以后有需要就能直接拿来用了;

demo的功能简介

此demo是个父子结构的maven工程,两个子工程特点如下:

整个服务如下图所示:

  1. 写操作:用户通过浏览器向service-a发起请求,通过service-a将数据写入mysql,然后service-a会调用service-b的接口,将数据写入redis;
  2. 读操作:用户通过浏览器向service-a发起请求,service-a会调用service-b的接口从redis中取数据,如果取到了就返回给浏览器,如果取不到,就从mysql中取,如果从mysql中能取到,就先通过service-b写入redis,再返回给浏览器,如果mysql中也没有,就返回无数据;

版本信息参考

  1. 操作系统:CentOS Linux release 7.7.1908
  2. docker:Community 19.03.2
  3. springboot:2.0.5.RELEASE
  4. mysql:5.7.27
  5. redis:5.0.6

demo源码下载

如果您不想编码,可以直接从GitHub下载完整的demo工程源码,地址和链接信息如下表所示:

项目主页
​​​https://github.com/zq2599/blog_demos​​​
该项目在GitHub上的主页
git仓库地址
(https) ​​​https://github.com/zq2599/blog_demos.git​​​
该项目源码的仓库地址,https协议
git仓库地址(ssh)
git@github.com:zq2599/blog_demos.git
该项目源码的仓库地址,ssh协议

这个git项目中有多个文件夹,本章的应用在pinpoint185demo文件夹下,如下图红框所示:

快速部署mysql

  1. 为了快速准备好mysql服务用来测试,我这里是用docker来完成的,一行命令即可:

docker run --name mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=888888 -idt mysql:5.7.27

  1. 创建数据库demo和表student,表结构非常简单:

CREATE DATABASE demo;
USE demo;
CREATE TABLE student (id INT(11), name VARCHAR(128));

快速部署redis

为了快速准备好redis服务用来测试,我这里是用docker来完成的,一行命令即可:

docker run --name redis -p 6379:6379 -idt redis:5.0.6 redis-server --appendonly yes

父工程

  1. 首先创建名为pinpoint185demo的maven工程,pom.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<modules>
<module>service-a</module>
<module>service-b</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>pinpoint185demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring.boot.version>2.0.5.RELEASE</spring.boot.version>
</properties>
<!--编译管理 jdk版本和字符集编码-->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>

子工程service-a编码

  1. 在此工程下创建子工程service-a,其pom.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>pinpoint185demo</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>service-a</artifactId>
<name>service-a</name>
<description>服务a</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

以上内容有几点需要注意:

a. 要提供web服务,所以依赖了spring-boot-starter-web;

b. 要使用mybaits,所以依赖了mybatis-spring-boot-starter;

c. 要连接mysql,所以依赖了mysql-connector-java;

d. commons-lang3、fastjson作为工具类,在代码中会用到它们的API;

  1. service-a的系统配置application.yml内容如下,注意数据库和mybaits的配置:

server:
port: 8080
spring:
datasource:
username: root
password: 888888
url: jdbc:mysql://192.168.121.143:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver

mybatis:
mapper-locations: classpath:mapping/*Mapping.xml
type-aliases-package: com.bolingcavalry.servicea.entity

logging:
level:
com:
bolingcavalry:
servicea: debug

# service-b的服务url
serviceb:
baseurl: http://localhost:8081/

  1. mybatis的mapping文件在src\main\resources\mapping目录,名为StudentMapping.xml,对应student表的定义和操作:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bolingcavalry.servicea.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.bolingcavalry.servicea.entity.Student">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
</resultMap>
<select id="getById" resultType="com.bolingcavalry.servicea.entity.Student">
select * from student where id = #{id}
</select>
<insert id="insert" parameterType="com.bolingcavalry.servicea.entity.Student" >
insert into student (id, name) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR})
</insert>
</mapper>

  1. student表对应的实体类:

package com.bolingcavalry.servicea.entity;

/**
* @Description: student entity
* @author: willzhao E-mail: zq2599@gmail.com
* @date: 2019/10/3 9:55
*/
public class Student {

private Integer id;

private String name;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

  1. student对应的mapper接口:

package com.bolingcavalry.servicea.mapper;

import com.bolingcavalry.servicea.entity.Student;
import org.springframework.stereotype.Repository;

/**
* @Description: mybatis mapper
* @author: willzhao E-mail: zq2599@gmail.com
* @date: 2019/10/3 9:58
*/
@Repository
public interface StudentMapper {

Student getById(Integer id);

void insert(Student student);
}

  1. 由于要用到restTemplate访问service-b,因此要增加对应的配置类:

package com.bolingcavalry.servicea.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
* @Description: 远程请求的配置
* @author: willzhao E-mail: zq2599@gmail.com
* @date: 2019/10/3 11:45
*/
@Configuration
public class RestTemplateConfig {

@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}

@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(15000);
factory.setReadTimeout(5000);
return factory;
}
}

  1. 接下来是提供web服务的controller:

package com.bolingcavalry.servicea.controller;

import com.alibaba.fastjson.JSON;
import com.bolingcavalry.servicea.entity.Student;
import com.bolingcavalry.servicea.mapper.StudentMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
* @Description: 提供学生服务相关的web接口
* @author: willzhao E-mail: zq2599@gmail.com
* @date: 2019/10/3 8:51
*/
@RestController
public class StudentController {

@Autowired
StudentMapper studentMapper;

@Autowired
private RestTemplate restTemplate;

@Value("${serviceb.baseurl}")
private String baseUrl;

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public String get(@PathVariable("id") Integer id) {

String rlt = restTemplate.getForObject(baseUrl + "get/" + id,String.class);

if(StringUtils.isNotBlank(rlt)){
return "From redis :" + rlt;
}

//redis中查不到,就去数据库里面查
Student student = studentMapper.getById(id);
//mysql里面也没有就报错
if(null==student) {
return "student with id["+id+"] not exist";
}
//调用service-b的接口,写入redis
restTemplate.getForObject(baseUrl + "set/"+id+"/"+student.getName(),String.class);

return "From mysql :"+JSON.toJSONString(student);
}

@RequestMapping(value = "/add/{id}/{name}", method = RequestMethod.GET)
public String add(@PathVariable("id") Integer id, @PathVariable("name") String name) {
Student student = new Student();
student.setId(id);
student.setName(name);
//写入数据库
studentMapper.insert(student);
//调用service-b的接口,写入redis
restTemplate.getForObject(baseUrl + "set/"+id+"/"+name,String.class);
return "insert success";
}
}

  1. 整个应用的启动类,增加了MapperScan注解:

package com.bolingcavalry.servicea;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.bolingcavalry.servicea.mapper")
public class ServiceAApplication {

public static void main(String[] args) {
SpringApplication.run(ServiceAApplication.class, args);
}
}

以上就是service-a的全部源码了,包括mybatis和restTmeplate操作;

service-b源码

  1. 创建名为service-b的子工程,pom.xml如下,要注意的是依赖了spring-boot-starter-data-redis和commons-pool2:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.bolingcavalry</groupId>
<artifactId>pinpoint185demo</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>service-b</artifactId>
<name>service-b</name>
<description>服务b</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

  1. 应用的配置文件application.properties内容如下:

server.port=8081
#redis
spring.redis.host=192.168.121.144
spring.redis.port=6379
# 数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
spring.redis.timeout=60s
# 连接池配置,2.0中直接使用jedis或者lettuce配置连接池
# 最大活跃连接数,负数为不限制
spring.redis.lettuce.pool.max-active=50
# 等待可用连接的最大时间,负数为不限制
spring.redis.lettuce.pool.max-wait=-1ms
# 最大空闲连接数
spring.redis.lettuce.pool.max-idle=10
# 最小空闲连接数
spring.redis.lettuce.pool.min-idle=2

  1. redis的配置类:

package com.example.serviceb.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;

/**
* @Description: (这里用一句话描述这个类的作用)
* @author: willzhao E-mail: zq2599@gmail.com
* @date: 2019/10/3 11:06
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

/**
* retemplate相关配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {

RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);

//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);

// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());

// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();

return template;
}

/**
* 对hash类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForHash();
}

/**
* 对redis字符串类型数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForValue();
}

/**
* 对链表类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForList();
}

/**
* 对无序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForSet();
}

/**
* 对有序集合类型的数据操作
*
* @param redisTemplate
* @return
*/
@Bean
public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
return redisTemplate.opsForZSet();
}
}

  1. redis的工具类:

package com.example.serviceb.util;

/**
* @Description: (这里用一句话描述这个类的作用)
* @author: willzhao E-mail: zq2599@gmail.com
* @date: 2019/10/3 11:09
*/
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 java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
* redisTemplate封装
*/
@Component
public class RedisUtil {

@Autowired
private RedisTemplate<String, Object> redisTemplate;

public RedisUtil(RedisTemplate<String, Object> 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 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}

/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
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(CollectionUtils.arrayToList(key));
}
}
}

//============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}

/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
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 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
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 要增加几(大于0)
* @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 要减少几(小于0)
* @return
*/
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}

//================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}

/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map<Object,Object> hmget(String key){
return redisTemplate.opsForHash().entries(key);
}

/**
* HashSet
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String,Object> map){
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* HashSet 并设置时间
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String,Object> map, long time){
try {
redisTemplate.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key,String item,Object value,long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 删除hash表中的值
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item){
redisTemplate.opsForHash().delete(key,item);
}

/**
* 判断hash表中是否有该项的值
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item){
return redisTemplate.opsForHash().hasKey(key, item);
}

/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item, by);
}

/**
* hash递减
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item,-by);
}

//============================set=============================
/**
* 根据key获取Set中的所有值
* @param key 键
* @return
*/
public Set<Object> sGet(String key){
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 根据value从一个set中查询,是否存在
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key,Object value){
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 将数据放入set缓存
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object...values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}

/**
* 将set数据放入缓存
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key,long time,Object...values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if(time>0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}

/**
* 获取set缓存的长度
* @param key 键
* @return
*/
public long sGetSetSize(String key){
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}

/**
* 移除值为value的
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object ...values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
//===============================list=================================

/**
* 获取list缓存的内容
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end){
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 获取list缓存的长度
* @param key 键
* @return
*/
public long lGetListSize(String key){
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}

/**
* 通过索引 获取list中的值
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key,long index){
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 将list放入缓存
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 将list放入缓存
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 根据索引修改list中的某条数据
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index,Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}

/**
* 移除N个值为value
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key,long count,Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}

}

  1. 保存student数据的实体类:

package com.example.serviceb.entity;

import java.io.Serializable;

/**
* @Description: (这里用一句话描述这个类的作用)
* @author: willzhao E-mail: zq2599@gmail.com
* @date: 2019/10/3 11:11
*/
public class Student implements Serializable {
private Integer id;
private String name;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

  1. 提供http服务的controller类:

package com.example.serviceb.controller;

import com.alibaba.fastjson.JSON;
import com.example.serviceb.entity.Student;
import com.example.serviceb.util.RedisUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
* @Description: redis服务
* @author: willzhao E-mail: zq2599@gmail.com
* @date: 2019/10/3 11:13
*/
@RestController
public class StudentRedisController {

@Resource
private RedisUtil redisUtil;

@RequestMapping(value = "/set/{id}/{name}", method = RequestMethod.GET)
public String set(@PathVariable("id") Integer id, @PathVariable("name") String name) {
Student student = new Student();
student.setId(id);
student.setName(name);
//写入redis,有效期是30秒
redisUtil.set("student:"+id, student, 30);
return "set successful, id ["+id+"], name ["+name+"]";
}

@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public String get(@PathVariable("id") Integer id) {
Object object = redisUtil.get("student:"+id);
return null==object ? "" : JSON.toJSONString(object);
}
}

  1. 最后是应用启动类:

package com.example.serviceb;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ServiceBApplication {

public static void main(String[] args) {
SpringApplication.run(ServiceBApplication.class, args);
}
}

以上就是整个demo的所有代码,接下来验证服务

验证

1、先调用service-a的add接口写数据:http://localhost:8080/add/1/tom :

2、检查数据库,写入成功:

mysql> select * from student;
+------+------+
| id | name |
+------+------+
| 1 | tom |
+------+------+
1 row in set (0.00 sec)

3、检查redis,写入成功(注意:千万不要在生产环境使用keys命令!!!):

127.0.0.1:6379> keys *
1) "student:1"
127.0.0.1:6379> get "student:1"
"[\"com.example.serviceb.entity.Student\",{\"id\":1,\"name\":\"tom\"}]"

4、等待超过30秒,调用读接口试试:http://localhost:8080/get/1 ,由于redis中的数据只有30秒有效期,所以此时页面提示数据来自mysql

5、立即再调用读接口,由于前面的一次读接口会将数据写入redis,所以此时页面提示数据来自redis:

至此,整个demo已经完成开发和验证,希望你在着手开发一个数据、缓存相关的springboot应用时,此demo能给你提供一些参考。

参考并致谢

本文的源码中,RedisConfig和RedisUtil这两个类参考了这篇文章的代码:​​https://www.jianshu.com/p/b9154316227e​​ ,在此致谢作者;

原作者:程序员欣宸

本文来自网络,不代表乐淘资源立场,转载请注明出处,如有侵权问题需要处理,请联系站长删除。联系QQ 917118162

作者: admin

上一篇
下一篇
广告位
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 917118162@qq.com

工作时间:周一至周五,9:00-17:30
关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部