1 新建spring项目
2 修改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>
<groupId>org.example</groupId>
<artifactId>spring-redis-mysql</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<mybatis.version>3.5.2</mybatis.version>
<mybatis-spring.version>2.0.2</mybatis-spring.version>
<spring.version>4.3.24.RELEASE</spring.version>
<druid.version>1.0.18</druid.version>
<mysql.version>8.0.17</mysql.version>
<fastjson.version>1.2.59</fastjson.version>
<!-- 注意只能使用2.0以下的版本 -->
<log4j.version>1.2.17</log4j.version>
<jedis.version>3.1.0</jedis.version>
<lombok.verison>1.18.10</lombok.verison>
</properties>
<dependencies>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!-- 导入spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.verison}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
3 新建User类
package com.example.demo.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
/**
* 用户编号
*/
private Integer id;
/**
* 用户姓名
*/
private String name;
/**
* 用户地址
*/
private String address;
/**
* 出生时间
*/
private Date birth;
/**
* 是否删除1删除0未删除
*/
private Integer flag;
private static final long serialVersionUID = 1L;
}
4 新建UserMapper
package com.example.demo.mapper;
import com.example.demo.domain.User;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> queryAllUser();
}
5 生成UserMapper.xml
<?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.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.example.demo.domain.User">
<!--@mbg.generated-->
<!--@Table sys_user-->
<id column="id" jdbcType="INTEGER" property="id" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="address" jdbcType="VARCHAR" property="address" />
<result column="birth" jdbcType="TIMESTAMP" property="birth" />
<result column="flag" jdbcType="INTEGER" property="flag" />
</resultMap>
<sql id="Base_Column_List">
<!--@mbg.generated-->
id, `name`, address, birth, flag
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
<!--@mbg.generated-->
select
<include refid="Base_Column_List" />
from sys_user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
<!--@mbg.generated-->
delete from sys_user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.example.demo.domain.User" useGeneratedKeys="true">
<!--@mbg.generated-->
insert into sys_user (`name`, address, birth,
flag)
values (#{name,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}, #{birth,jdbcType=TIMESTAMP},
#{flag,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.example.demo.domain.User" useGeneratedKeys="true">
<!--@mbg.generated-->
insert into sys_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null">
`name`,
</if>
<if test="address != null">
address,
</if>
<if test="birth != null">
birth,
</if>
<if test="flag != null">
flag,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="name != null">
#{name,jdbcType=VARCHAR},
</if>
<if test="address != null">
#{address,jdbcType=VARCHAR},
</if>
<if test="birth != null">
#{birth,jdbcType=TIMESTAMP},
</if>
<if test="flag != null">
#{flag,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.example.demo.domain.User">
<!--@mbg.generated-->
update sys_user
<set>
<if test="name != null">
`name` = #{name,jdbcType=VARCHAR},
</if>
<if test="address != null">
address = #{address,jdbcType=VARCHAR},
</if>
<if test="birth != null">
birth = #{birth,jdbcType=TIMESTAMP},
</if>
<if test="flag != null">
flag = #{flag,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.demo.domain.User">
<!--@mbg.generated-->
update sys_user
set `name` = #{name,jdbcType=VARCHAR},
address = #{address,jdbcType=VARCHAR},
birth = #{birth,jdbcType=TIMESTAMP},
flag = #{flag,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
<select id="queryAllUser" resultMap="BaseResultMap">
<!--@mbg.generated-->
select
<include refid="Base_Column_List" />
from sys_user
</select>
</mapper>
6 生成UserService
package com.example.demo.service;
import com.example.demo.domain.User;
import java.util.List;
public interface UserService{
int deleteByPrimaryKey(Integer id);
User insert(User user);
User selectByPrimaryKey(Integer id);
User updateByPrimaryKey(User user);
List<User> queryAllUser();
}
7 生成UserServiceImpl
package com.example.demo.service.impl;
import com.example.demo.domain.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public int deleteByPrimaryKey(Integer id) {
return this.userMapper.deleteByPrimaryKey(id);
}
@Override
public User insert(User user) {
this.userMapper.insert(user);
return user;
}
@Override
public User selectByPrimaryKey(Integer id) {
return this.userMapper.selectByPrimaryKey(id);
}
@Override
public User updateByPrimaryKey(User user) {
int index = this.userMapper.updateByPrimaryKey(user);
return user;
}
@Override
public List<User> queryAllUser() {
return this.userMapper.queryAllUser();
}
}
8 创建application-redis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--声明配置-->
<bean id="poolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig">
<property name="maxTotal" value="100"></property>
<property name="maxIdle" value="80"></property>
<property name="minIdle" value="20"></property>
<property name="maxWaitMillis" value="2000"></property>
<property name="testOnBorrow" value="true"></property>
</bean>
<!--jedispool-->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
<!--因为JedisPool没有属性 所以只能使用构造器的注入方式-->
<constructor-arg name="poolConfig" ref="poolConfig"></constructor-arg>
<constructor-arg name="host" value="192.168.222.131"></constructor-arg>
<constructor-arg name="port" value="6379"></constructor-arg>
<constructor-arg name="timeout" value="2000"></constructor-arg>
<constructor-arg name="password" value="123456"></constructor-arg>
</bean>
</beans>
9 创建application-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 引入db.properties -->
<context:property-placeholder
location="classpath*:db.properties" system-properties-mode="FALLBACK" />
<!-- 声明dataSource -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 注入连接属性 -->
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
</bean>
<!-- 声明sessionFactory 并注入mybatis.cfg.xml -->
<bean id="sqlSessionFactory"
class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据源 -->
<property name="dataSource" ref="dataSource"></property>
<!-- 注入mapper.xml -->
<property name="mapperLocations">
<array>
<value>classpath:mapper/*Mapper.xml</value>
</array>
</property>
</bean>
<!-- 扫描mapper接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入mapper接口所在的包 注意多个包的情况的配置 -->
<property name="basePackage">
<value>
com.example.demo.mapper
</value>
</property>
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName"
value="sqlSessionFactory"></property>
</bean>
</beans>
10 创建application-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.example.demo.service.impl"></context:component-scan>
<!-- 1,声明事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 启动注解事务 -->
<!-- <tx:annotation-driven/> -->
<!-- 2,声明事务的传播特性 也就是通知 -->
<tx:advice id="advise" transaction-manager="transactionManager">
<tx:attributes>
<!-- 以add开头的方法名需要事务 -->
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="change*" propagation="REQUIRED"/>
<tx:method name="reset*" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="load*" read-only="true"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 3进行AOP织入 -->
<aop:config>
<!-- 声明切面 -->
<aop:pointcut expression="execution(* com.example.demo.service.impl.*.*(..))" id="pc"/>
<!-- 织入 -->
<aop:advisor advice-ref="advise" pointcut-ref="pc"/>
</aop:config>
</beans>
11 创建CacheUserAspect
package com.example.demo.cache;
import com.alibaba.fastjson.JSON;
import com.example.demo.domain.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.io.Serializable;
@Component
@Aspect
@EnableAspectJAutoProxy
public class CacheUserAspect {
private Log log= LogFactory.getLog(CacheUserAspect.class);
public static final String POINTCUT_ADD="execution(* com.example.demo.service.impl.UserServiceImpl.insert(..))";
public static final String POINTCUT_UPDATE="execution(* com.example.demo.service.impl.UserServiceImpl.updateByPrimaryKey(..))";
public static final String POINTCUT_DELETE="execution(* com.example.demo.service.impl.UserServiceImpl.deleteByPrimaryKey(..))";
public static final String POINTCUT_GETONE="execution(* com.example.demo.service.impl.UserServiceImpl.selectByPrimaryKey(..))";
//redis里面的前缀
public static final String PROFIX="user:";
//注入JedisPool
@Autowired
private JedisPool jedisPool;
@Around(value = CacheUserAspect.POINTCUT_ADD)
public Object cacheAddUser(ProceedingJoinPoint pjp) throws Throwable {
//插入数据库
User user = (User) pjp.proceed();
Jedis jedis = jedisPool.getResource();
//把user转成json串
String json= JSON.toJSONString(user);
jedis.set(PROFIX+user.getId(),json);
log.info(PROFIX+user.getId()+"数据已存入到Redis");
jedis.close();
return user;
}
@Around(value = CacheUserAspect.POINTCUT_UPDATE)
public Object cacheUpdateUser(ProceedingJoinPoint pjp) throws Throwable {
//修改数据库
User user = (User) pjp.proceed();
Jedis jedis = jedisPool.getResource();
//把user转成json串
String json= JSON.toJSONString(user);
jedis.set(PROFIX+user.getId(),json);
log.info(PROFIX+user.getId()+"数据已更新到Redis");
jedis.close();
return user;
}
@Around(value = CacheUserAspect.POINTCUT_DELETE)
public Object cacheDeleteUser(ProceedingJoinPoint pjp) throws Throwable {
//删除数据库
Serializable id = (Serializable) pjp.getArgs()[0];
log.info(PROFIX+id+"数据库数据已删除");
Jedis jedis = jedisPool.getResource();
if(jedis.exists(PROFIX+id)){
jedis.del(PROFIX+id);
log.info(PROFIX+id+"数据已从Redis删除");
}
jedis.close();
return id;
}
@Around(value = CacheUserAspect.POINTCUT_GETONE)
public Object cacheGetOneUser(ProceedingJoinPoint pjp) throws Throwable {
Serializable id = (Serializable) pjp.getArgs()[0];
if(null==id){
return null;
}
Jedis jedis = jedisPool.getResource();
String json = jedis.get(PROFIX + id);
if(null!=json){
User user=JSON.parseObject(json,User.class);
log.info(PROFIX+id+"已从redis里机查询到数据");
jedis.close();
return user;
}else{
log.info(PROFIX+id+"缓存里面没有数据,要从数据库里面查询");
User user= (User) pjp.proceed();
if(null!=user){
jedis.set(PROFIX+user.getId(),JSON.toJSONString(user));
log.info(PROFIX+id+"数据已存入redis");
}
jedis.close();
return user;
}
}
}
12 创建application-cache.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example.demo.cache"></context:component-scan>
</beans>
13 创建applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath*:application-dao.xml"></import>
<import resource="classpath*:application-service.xml"></import>
<import resource="classpath*:application-redis.xml"></import>
<import resource="classpath*:application-cache.xml"></import>
</beans>
14 TestApp测试类
package com.example.demo.test;
import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Date;
import java.util.List;
public class TestApp {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
UserService userService = context.getBean(UserService.class);
List<User> users = userService.queryAllUser();
for (User user : users) {
System.out.println(user);
}
User user=new User();
user.setName("xiaoqiang");
user.setAddress("bj");
user.setBirth(new Date());
user.setFlag(0);
userService.insert(user);
// User user = userService.selectByPrimaryKey(113);
// System.out.println(user);
// user.setName("xiaoming");
// user.setAddress("wh");
// userService.updateByPrimaryKey(user);
// userService.deleteByPrimaryKey(112);
System.out.println("操作成功");
}
}