Spring boot集成Redis

学到Spring boot集成Redis,写了个小demo练习,Redis缓存在service层使用

目录

1、项目结构

2、SQL、配置文件

2.1、SQL

2.2、application.properties

2.3、pom.xml

3.定义实体类

4、自定义SpringMVC返回类型

4.1、返回类型实体

4.2、返回类

5、mapper和mapper.xml

5.1、mapper

5.2、mapper.xml

6、service和serviceimpl

6.1、service

6.2、serviceimpl

7、controller

8、启动类

9、测试


1、项目结构

                            

2、SQL、配置文件

2.1、SQL

/*
Navicat MySQL Data Transfer

Source Server         : llangzh
Source Server Version : 80016
Source Host           : localhost:3306
Source Database       : myredis

Target Server Type    : MYSQL
Target Server Version : 80016
File Encoding         : 65001

Date: 2019-05-13 13:24:59
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'a', 'a');
INSERT INTO `user` VALUES ('2', 'b', 'b');

2.2、application.properties

# 连接池配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/myredis?serverTimezone=GMT%2B8&userUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456

# 类别名
mybatis.type-aliases-package=com.llangzh.bean
#mapper.xml配置文件位置
mybatis.mapper-locations=classpath:mapper/*.xml

# Redis缓存
#spring.redis.host=127.0.0.1
#spring.redis.port=6379
# 如果Redis缓存没有设置密码,不用配置password
#spring.redis.password=123456



# Redis哨兵模式
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=192.168.106.128:26380,192.168.106.128:26382,192.168.106.128:26384
#spring.redis.password=123456

2.3、pom.xml

<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>
	<groupId>com.llangzh</groupId>
	<artifactId>MySpringbootRedis</artifactId>

	<version>1.0.0</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.4.RELEASE</version>
	</parent>

	<dependencies>
		<!-- Spring boot启动 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- Spring boot集成Redis -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

		<!-- Spring boot集成Mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.1</version>
		</dependency>

		<!-- MySQL驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
		</dependency>

		<!-- Druid连接池 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.16</version>
		</dependency>
		
		<!-- spring boot热加载 -->
		<dependency>
	        <groupId>org.springframework.boot</groupId>
	        <artifactId>spring-boot-devtools</artifactId>
	        <optional>true</optional>
	    </dependency>
	</dependencies>

	<build>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.xml</include>
				</includes>
			</resource>
		</resources>
	
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<!-- spring boot热加载 -->
				<configuration>       
	                <fork>true</fork>
	            </configuration>
			</plugin>
		</plugins>
	</build>
</project>

3.定义实体类

对实体类进行序列化

package com.llangzh.bean;

import java.io.Serializable;

/**
 * User实体类
 * 
 * @author Administrator
 *
 */
public class User implements Serializable{
	private static final long serialVersionUID = 1L;
	
	private Integer id;
	private String username;
	private String password;
	
	public User() {	}
	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}

	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}

4、自定义SpringMVC返回类型

4.1、返回类型实体

package com.llangzh.model;

public class Modal {
	private int code;
	private boolean success;
	private String message;

	public Modal() {
		super();
	}
	public Modal(int code, boolean success, String message) {
		super();
		this.code = code;
		this.success = success;
		this.message = message;
	}

	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public boolean isSuccess() {
		return success;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}

4.2、返回类

package com.llangzh.model;

import java.io.Serializable;

public class ResponseModal extends Modal implements Serializable{

	private static final long serialVersionUID = 1L;

	private Object response;
	
	public ResponseModal(){	
	}
	public ResponseModal(int code,boolean success,String message,Object obj){
		super(code,success,message);
		this.response = obj;
	}

	public Object getResponse() {
		return response;
	}
	public void setResponse(Object response) {
		this.response = response;
	}
}

5、mapper和mapper.xml

5.1、mapper

package com.llangzh.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import com.llangzh.bean.User;

@Mapper
public interface IRedisMapper {
	
	/**
	 * 查询所有
	 * 
	 * @return
	 */
	List<User> selectAllUser();

}

5.2、mapper.xml

<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.llangzh.mapper.IRedisMapper">

	<resultMap type="User" id="userlist">
		<id column="id" property="id"/>
		<result column="username" property="username"/>
		<result column="password" property="password"/>
	</resultMap>

	<!-- 查询所有 -->
	<select id="selectAllUser" resultMap="userlist">
		SELECT id,username,password FROM `user`
	</select>
	
</mapper>

6、service和serviceimpl

6.1、service

package com.llangzh.service;

import java.util.List;

import com.llangzh.bean.User;

public interface IRedisService {
	
	List<User> findAllUser();

}

6.2、serviceimpl

在service层使用Redis缓存

package com.llangzh.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import com.llangzh.bean.User;
import com.llangzh.mapper.IRedisMapper;
import com.llangzh.service.IRedisService;

@Service
public class RedisServiceImpl implements IRedisService{
	
	@Autowired
	private IRedisMapper redisMapper;

	@Autowired
	private RedisTemplate<Object,Object> redisTemplate;
	
	@Override
	public List<User> findAllUser() {
		
		//使用Redis字符串序列化器
		RedisSerializer<String> redisSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(redisSerializer);
		JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer(); 
		redisTemplate.setValueSerializer(jdkSerializationRedisSerializer);
		
		//查询Redis缓存
		List<User> users = (List<User>) redisTemplate.opsForValue().get("allUser");

		//使用双重检测锁解决高并发时的缓存穿透问题
		if(users == null) {
			synchronized (this) {
				users = (List<User>) redisTemplate.opsForValue().get("allUser");
				if(users == null) {
					//Redis缓存中没有数据,到数据库中查找,并放入Redis缓存中
					users = redisMapper.selectAllUser();
					System.out.println(users);
					redisTemplate.opsForValue().set("allUser", users);
				}
			}
		}
		return users;
	}
}

7、controller

package com.llangzh.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.llangzh.bean.User;
import com.llangzh.model.ResponseModal;
import com.llangzh.service.IRedisService;

@RestController
public class RedisController {

	@Autowired
	private IRedisService redisService;
	
	@RequestMapping("/findAllUser")
	public ResponseModal findAllUser() {
		List<User> users = redisService.findAllUser();
		ResponseModal modal = new ResponseModal(200,true,"所有User",users);
		return modal;
	}
}

8、启动类

package com.llangzh;

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

@SpringBootApplication
public class App {

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

9、测试

启动MySQL数据库、Redis缓存

使用java Application启动项目

浏览器url:http://localhost:8080/findAllUser

返回值:

{"code":200,"success":true,"message":"所有User","response":[{"id":1,"username":"a","password":"a"},{"id":2,"username":"b","password":"b"}]}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值