Spring基于注解整合Redis完整实例

网友投稿 265 2023-05-22


Spring基于注解整合Redis完整实例

在《Redis之——Spring整合Redis》一文中,向大家介绍了如何将spring与Redis整合起来,但不是基于注解的形式,很多同学都希望能够通过注解的形式来简单的将Spring与Redis整合起来,这样,在使用的时候,只需要在相应的方法上加上注解,便可以使方法轻松的调用Redis的缓存。那么今天就来向大家介绍如何用基于注解的形式来整合Spring与Redis。

一、项目搭建

今天,我们不使用hibernate来操作数据库了,我们今天选择的框架是: Spring4(包括mvc、context、orm) + MyBatis3,所以,我们今天的基础架构是:Spring4(包括mvc、context、orm) + MyBatis3+Redis

1、构建pom.xml

xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://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">

4.0.0

lyz

lyz

1.0.0

war

lyz

Basic Data Platform

UTF-8

4.2.0.RELEASE

org.springframework

spring-context

${spring.version}

org.springframework

spring-aop

${spring.version}

org.springframework

spring-webmvc

${spring.version}

org.springframework

spring-web

${spring.version}

javax.servlet

jstl

1.2

commons-logging

commons-logging

1.1.3

org.codehaus.jackson

jackson-mapper-asl

1.9.13

com.fasterxml.jackson.core

jackson-annotations

2.6.1

com.fasterxml.jackson.core

jackson-core

2.6.1

com.fasterxml.jackson.core

jackson-databind

2.6.1

org.springframework

spring-orm

${spring.version}

org.mybatis

mybatis-spring

1.2.3

mysql

mysql-connector-java

5.1.36

org.mybatis

mybatis

3.3.0

c3p0

c3p0

0.9.1.2

org.slf4j

slf4j-log4j12

1.7.12

log4j

log4j

1.2.17

org.springframework.data

spring-data-redis

1.6.0.RELEASE

redis.clients

jedis

2.7.3

maven-compiler-plugin

3.1

1.7

1.7

maven-war-plugin

2.4

WebContent

false

xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://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">

4.0.0

lyz

lyz

1.0.0

war

lyz

Basic Data Platform

UTF-8

4.2.0.RELEASE

org.springframework

spring-context

${spring.version}

org.springframework

spring-aop

${spring.version}

org.springframework

spring-webmvc

${spring.version}

org.springframework

spring-web

${spring.version}

javax.servlet

jstl

1.2

commons-logging

commons-logging

1.1.3

org.codehaus.jackson

jackson-mapper-asl

1.9.13

com.fasterxml.jackson.core

jackson-annotations

2.6.1

com.fasterxml.jackson.core

jackson-core

2.6.1

com.fasterxml.jackson.core

jackson-databind

2.6.1

org.springframework

spring-orm

${spring.version}

org.mybatis

mybatis-spring

1.2.3

mysql

mysql-connector-java

5.1.36

org.mybatis

mybatis

3.3.0

c3p0

c3p0

0.9.1.2

org.slf4j

slf4j-log4j12

1.7.12

log4j

log4j

1.2.17

org.springframework.data

spring-data-redis

1.6.0.RELEASE

redis.clients

jedis

2.7.3

maven-compiler-plugin

3.1

1.7

1.7

maven-war-plugin

2.4

WebContent

false

2、创建测试数据库:lyz,测试数据表:user

DROP DATABASE IF EXISTS `lyz`;

CREATE DATABASE `lyz`;

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (

`id` int(10) unsigned NOT NULL AUTO_INCREMENT,

`name` varchar(255) DEFAULT NULL,

`sex` varchar(255) DEFAULT NULL,

`age` int(11) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3、创建实体类user

package com.lyz.user.bean;

import java.io.Serializable;

import org.codehaus.jackson.map.annotate.JsonSerialize;

import com.fasterxml.jackson.databind.PropertyNamingStrategy;

import com.fasterxml.jackson.databind.annotation.JsonNaming;

/**

* 用户实体类

* @author liuyazhuang

*

*/

@JsonSerialize

@JsonNaming(PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy.class)

public class User implements Serializable{

private static final long serialVersionUID = 1332643889208978231L;

/**

* id

*/

private Integer id;

/**

* 姓名

*/

private String name;

/**

* 性别

*/

private String sex;

/**

* 年龄

*/

private Integer age;

public User() {

super();

}

public User(Integer id, String name) {

super();

this.id = id;

this.name = name;

}

public User(String name, String sex, Integer age) {

super();

this.name = name;

this.sex = sex;

this.age = age;

}

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;

}

public String getSex() {

return sex;

}

public void setSex(String sex) {

this.sex = sex;

}

public Integer getAge() {

return age;

}

public void setAge(Integer age) {

this.age = age;

}

@Override

public String toString() {

return "User [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + "]";

}

}

4、创建UserMapper接口

此接口定义了与MyBatis交互的接口协议,通过此接口与MyBatis框架通信,由MyBatis框架实现对数据库的增删改查操作。

package com.lyz.user.mapper;

import java.util.List;

import com.lyz.user.bean.User;

/**

* UserMapper接口

* @author liuyazhuang

*

*/

public interface UserMapper {

/**

* 保存用户

* @param user

*/

void saveUser(User user);

/**

* 获取所有用户列表

* @return

*/

List getAllUser();

/**

* 根据id查询用户信息

* @param id

* @return

*/

User getUserById(Integer id);

/**

* 更新用户的名称

* @param user

*/

void renameUser(User user);

/**

* 根据id删除指定的用户

* @param id

*/

void deleteUserById(Integer id);

}

5、创建UserMapper.xml

此文件中主要实现了UserMapper接口定义的方法,即实现对数据库的增删改查操作。

insert into user (name, sex, age)

values ( #{name}, #{sex}, #{age} )

select u.id, u.name, u.sex, u.age from user u

select u.id, u.name, u.sex, u.age from user u where u.id = #{id}

update user set name = #{name} where id = #{id}

delete from user where id = #{id}

6、创建UserDao接口

package com.lyz.user.dao;

import java.util.List;

import com.lyz.user.bean.User;

/**

* 用户dao接口

* @author liuyazhuang

*

*/

public interface UserDao {

/**

* 保存用户

* @param user

*/

void saveUser(User user);

/**

* 获取所有用户列表

* @return

*/

List getAllUser();

/**

* 根据id查询用户信息

* @param id

* @return

*/

User getById(Integer id);

/**

* 更新用户的名称

* @param user

*/

void rename(User user);

/**

* 根据id删除指定的用户

* @param id

*/

void deleteById(Integer id);

}

7、创建UserDao的实现类UserDaoImpl

此类主要实现UserDao中定义的接口,主要实现方法是注入UserMapper接口的实例对象,调用UserMapper接口实例的方法来实现相应的操作。

package com.lyz.user.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.lyz.user.bean.User;

import com.lyz.user.dao.UserDao;

import com.lyz.user.mapper.UserMapper;

/**

* Dao实现类

* @author liuyazhuang

*

*/

@Repository

public class UserDaoImpl implements UserDao {

@Resource

private UserMapper mUserMapper;

@Override

public void saveUser(User user) {

mUserMapper.saveUser(user);

}

@Override

public List getAllUser() {

return mUserMapper.getAllUser();

}

@Override

public User getById(Integer id) {

return mUserMapper.getUserById(id);

}

@Override

public void rename(User user) {

mUserMapper.renameUser(user);

}

@Override

public void deleteById(Integer id) {

mUserMapper.deleteUserById(id);

}

}

8、创建UserService接口

package com.lyz.user.service;

import java.util.List;

import com.lyz.user.bean.User;

/**

* 用户service接口

* @author liuyazhuang

*

*/

public interface UserService {

/**

* 保存用户

* @param user

*/

void saveUser(String name, String sex, Integer age);

/**

* 获取所有用户列表

* @return

*/

List getAllUser();

/**

* 根据id查询用户信息

* @param id

* @return

*/

User getUserById(Integer id);

/**

* 更新用户的名称

* @param user

*/

void renameUser(String name, Integer id);

/**

* 根据id删除指定的用户

* @param id

*/

void deleteUserById(Integer id);

}

9、创建UserService接口实现类UserServiceImpl

package com.lyz.user.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Propagation;

import org.springframework.transaction.annotation.Transactional;

import com.lyz.user.bean.User;

import com.lyz.user.dao.UserDao;

import com.lyz.user.service.UserService;

/**

* UserService实现类

* @author liuyazhuang

*

*/

@Service

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)

public class UserServiceImpl implements UserService {

@Resource

private UserDao mUserDao;

@Override

@CacheEvict(value = { "saveUser"}, allEntries = true)

public void saveUser(String name, String sex, Integer age) {

User user = new User(name, sex, age);

mUserDao.saveUser(user);

}

@Override

@Cacheable("getAllUser")

public List getAllUser() {

return mUserDao.getAllUser();

}

@Override

@Cacheable("getUserById")

public User getUserById(Integer id) {

return mUserDao.getById(id);

}

@Override

@CacheEvict(value = { "getAllUser", "getUserById" }, allEntries = true)

public void renameUser(String name, Integer id) {

mUserRWgQubErXDao.rename(new User(id, name));

}

@Override

@CacheEvict(value = { "getAllUser", "getUserById" }, allEntries = true)

public void deleteUserById(Integer id) {

mUserDao.deleteById(id);

}

}

10、创建UserController

package com.lyz.user.controller;

import java.util.List;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import com.lyz.user.bean.User;

import com.lyz.user.service.UserService;

/**

* UserController类

* @author liuyazhuang

*

*/

@Controller

@RequestMapping("/user")

public class UserController {

private final Log logger = LogFactory.getLog(this.getClass());

@Autowired

private UserService mUserService;

/**

* 保存用户

* @param name

* @param sex

* @param age

* @return

*/

@RequestMapping("/save")

@ResponseBody

public Integer save(@RequestParam(value="name", defaultValue="") String name,

@RequestParam(value="sex", defaultValue="") String sex,

@RequestParam(value="age", defaultValue="0") String age){

logger.debug(name);

mUserService.saveUser(name, sex, Integer.parseInt(age));

return 1;

}

/**

* 获取所有用户列表

* @return

*/

@RequestMapping("/getall")

@ResponseBody

public Object getAllUser(){

List users = mUserService.getAllUser();

for(User u : users){

logger.debug(u.toString());

}

return users;

}

/**

* 根据用户id获取用户信息

* @return

*/

@RequestMapping("/getUserById")

@ResponseBody

public Object getUserById(@RequestParam(value="id", defaultValue="0") String id){

User user = mUserService.getUserById(Integer.parseInt(id));

logger.debug(user.toString());

return user;

}

/**

* 根据用户id获取用户信息

* @return

*/

@RequestMapping("/renameUser")

@ResponseBody

public Integer renameUser(@RequestParam(value="id", defaultValue="0") String id,

@RequestParam(value="name", defaultValue="") String name){

logger.debug(id + "=========" + name);

mUserService.renameUser(name, Integer.parseInt(id));

return 1;

}

/**

* 根据用户id获取用户信息

* @return

*/

@RequestMapping("/delete")

@ResponseBody

public Integer delete(@RequestParam(value="id", defaultValue="0") String id){

logger.debug(id);

mUserService.deleteUserById(Integer.parseInt(id));

return 1;

}

}

到此,只要再创建相应的配置文件,我们就可以实现Spring+MyBatis框架的整合了,下面我们创建一个整合Redis的关键类RedisCacheConfig,这个类继承CachingConfigurerSupport。

11、创建RedisCacheConfig类

package com.lyz.cache.redis;

import java.lang.reflect.Method;

import org.springframework.cache.CacheManager;

import org.springframework.cache.annotation.CachingConfigurerSupport;

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.cache.interceptor.KeyGenerator;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

/**

* 以Spring与配置文件来管理的redis缓存配置类

* @author liuyazhuang

*

*/

@Configuration

@EnableCaching

public class RedisCacheConfig extends CachingConfigurerSupport {

private volatile JedisConnectionFactory mJedisConnectionFactory;

private volatile RedisTemplate mRedisTemplate;

private volatile RedisCacheManager mRedisCacheManager;

public RedisCacheConfig() {

super();

}

public RedisCacheConfig(JedisConnectionFactory mJedisConnectionFactory, RedisTemplate mRedisTemplate,

RedisCacheManager mRedisCacheManager) {

super();

this.mJedisConnectionFactory = mJedisConnectionFactory;

this.mRedisTemplate = mRedisTemplate;

this.mRedisCacheManager = mRedisCacheManager;

}

public JedisConnectionFactory redisConnectionFactory() {

return mJedisConnectionFactory;

}

public RedisTemplate redisTemplate(RedisConnectionFactory cf) {

return mRedisTemplate;

}

public CacheManager cacheManager(RedisTemplate, ?> redisTemplate) {

return mRedisCacheManager;

}

@Bean

public KeyGenerator customKeyGenerator() {

return new KeyGenerator() {

@Override

public Object generate(Object o, Method method, Object... objects) {

StringBuilder sb = new StringBuilder();

sb.append(o.getClass().getName());

sb.append(method.getName());

for (Object obj : objects) {

sb.append(obj.toString());

}

return sb.toString();

}

};

}

}

这个类中的所有属性、字段都是在Spring的配置文件lyz-applicationContext.xml文件中注入的,稍后我们介绍如何注入这些属性字段。

下面介绍每个配置文件的内容,注:所有的配置文件(除了web.xml),都是放在classpath路径下的。

12、创建数据库的配置文件jdbc.properties

jdbc.host=127.0.0.1

jdbc.database=lyz

jdbc.port=3306

jdbc.username=root

jdbc.password=root

13、创建log4j日志配置文件log4j.properties

# Global logging configuration

log4j.rootLogger=WARN,stdout

# Console output...

log4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n

# mybatis log

log4j.logger.com.lyz.user.mapper.UserMapper=DEBUG

# lyz log

log4j.logger.com.lyz.user.controller=DEBUG

log4j.logger.com.lyz.user.service=DEBUG

14、创建redis配置文件redis.properties

# Redis settings

redis.host=192.168.157.130

redis.port=6379

redis.pass=liuyazhuang

redis.dbIndex=0

redis.expiration=3000

redis.maxIdle=300

redis.maxActive=600

redis.maxWait=1000

redis.testOnBorrow=true

15、创建SpringMVC的配置文件lyzmvc-servlet.xml

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-4.0.xsd">

class="org.springframework.web.servlet.view.UrlBasedViewResolver">

value="org.springframework.web.servlet.view.JstlView" />

class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">

application/json;charset=UTF-8

xmlns:xsi="http://w3.org/2001/XMLSchema-instance" xmlns:p="http://springframework.org/schema/p"

xmlns:context="http://springframework.org/schema/context"

xsi:schemaLocation="http://springframework.org/schema/beans

http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/context

http://springframework.org/schema/context/spring-context-4.0.xsd">

class="org.springframework.web.servlet.view.UrlBasedViewResolver">

value="org.springframework.web.servlet.view.JstlView" />

class="org.springframework.web.servlet.view.UrlBasedViewResolver">

value="org.springframework.web.servlet.view.JstlView" />

value="org.springframework.web.servlet.view.JstlView" />

class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">

application/json;charset=UTF-8

class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">

application/json;charset=UTF-8

16、创建MyBatis配置文件mybatis-config.xml

17、创建Spring核心配置文件lyz-applicationContext.xml

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:aop="http://springframework.org/schema/aop"

xmlns:tx="http://springframework.org/schema/tx"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.0.xsd

http://springframework.org/schema/aop http://springframework.org/schema/aop/spring-aop-4.0.xsd

http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-4.0.xsd">

classpath:jdbc.properties

classpath:redis.properties

destroy-method="close">

xmlns:xsi="http://w3.org/2001/XMLSchema-instance"

xmlns:context="http://springframework.org/schema/context"

xmlns:aop="http://springframework.org/schema/aop"

xmlns:tx="http://springframework.org/schema/tx"

xsi:schemaLocation="http://springframework.org/schema/beans http://springframework.org/schema/beans/spring-beans-4.0.xsd

http://springframework.org/schema/context http://springframework.org/schema/context/spring-context-4.0.xsd

http://springframework.org/schema/aop http://springframework.org/schema/aop/spring-aop-4.0.xsd

http://springframework.org/schema/tx http://springframework.org/schema/tx/spring-tx-4.0.xsd">

classpath:jdbc.properties

classpath:redis.properties

destroy-method="close">

destroy-method="close">

注:在lyz-applicationContext.xml配置文件中,配置了Spring的注解、注入了RedisCacheConfig中的属性字段。

18、完善web.xml文件

xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">

lyz

encodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

forceEncoding

true

encodingFilter

/*

contextConfigLocation

/WEB-INF/classes/*-applicationContext.xml

org.springframework.web.context.ContextLoaderListener

lyzmvc

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

/WEB-INF/classes/*-servlet.xml

1

lyzmvc

*.json

*.html

xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">

lyz

encodingFilter

org.springframework.web.filter.CharacterEncodingFilter

encoding

UTF-8

forceEncoding

true

encodingFilter

/*

contextConfigLocation

/WEB-INF/classes/*-applicationContext.xml

org.springframework.web.context.ContextLoaderListener

lyzmvc

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

/WEB-INF/classes/*-servlet.xml

1

lyzmvc

*.json

*.html

二、运行测试

这里我们使用Apache JMeter来测试我们的程序,大家可以到http://jmeter.apache.org/download_jmeter.cgi下载Apache JMeter。

1、启动程序,使用JMeter调用保存用户接口

首先按照图示配置JMeter,其中访问路径和端口按照实际需要配置:

点击启动按钮,也就是上方的

图标:

点击“查看结果树”并打开“响应数据”选项:

我们看到返回的结果是1,证明我们成功的调用了保存用户的接口。

下面我们来看看数据库表:

已经将数据保存到数据库了。

2、调用查询用户的接口

首先按照图示配置JMeter,其中访问路径和端口按照实际需要配置:

这些我们先看看redis服务器中是否存在相应的数据:

此时,redis服务器中并没有任何数据,下面我们点击启动,执行程序:

点击“查看结果数”并打开“响应数据”,如下:

返回了相应的数据。

我们再打开控制台看看输出的语句:

说明首次获取数据是从数据库中获取的。下面我们再看看redis缓存中是否存在数据了:

说明首次获取数据,从数据库中取出的数据已经放在了redis缓存服务器中。

我们再次点击Jmeter的启动按钮,执行查询用户的操作:

查看Jmeter的“查看结果数”中的“响应数据”选项:

返回了正确的结果,同时,我们再看看Eclipse的控制台:

已经没有再从数据库中获取数据了,说明再次执行查询用户的操作,程序是直接从Redis缓存中获取的数据。

至此,Spring基于注解整合Redis介绍完毕。

三、源码下载

完整示例代码:Spring_Redis_jb51.rar


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:ES6新特性一: let和const命令详解
下一篇:Java软件编程培训机构靠谱吗
相关文章

 发表评论

暂时没有评论,来抢沙发吧~