ssm整合redis

ssm集成redis,这里本人就直接转载别人的,写的很详细的。就不再说明:原链接:https://www.cnblogs.com/liuzhihu/p/8259060.html

如果对您有帮助 ,请多多支持.多少都是您的心意与支持,一分也是爱,再次感谢!!!

 支付宝赞赏:记得点击下面的余额宝,红包可能要大些。注意:余额宝红包有效期三天(72小时) 在有效期内
余额宝红包使用完或过期才能有机会领取下个余额宝红包,感谢大家的支持!您的支持,我会继续分享更多的文章,欢迎关注!

Pom.xml

  

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

<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/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ssm</groupId>

    <artifactId>ssmDemo</artifactId>

    <packaging>war</packaging>

    <version>0.0.1-SNAPSHOT</version>

    <name>ssmDemo Maven Webapp</name>

    <url>http://maven.apache.org</url>

 

    <properties>

        <!-- spring版本号 -->

        <spring.version>4.0.2.RELEASE</spring.version>

        <!-- mybatis版本号 -->

        <mybatis.version>3.2.6</mybatis.version>

        <!-- log4j日志文件管理包版本 -->

        <slf4j.version>1.7.7</slf4j.version>

        <log4j.version>1.2.17</log4j.version>

    </properties>

 

    <dependencies>

        <dependency>

            <groupId>junit</groupId>

            <artifactId>junit</artifactId>

            <version>4.11</version>

            <!-- 表示开发的时候引入,发布的时候不会加载此包 -->

            <scope>test</scope>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-test</artifactId>

            <version>4.1.9.RELEASE</version>

            <scope>test</scope>

        </dependency>

        <dependency>

            <groupId>org.apache.commons</groupId>

            <artifactId>commons-lang3</artifactId>

            <version>3.5</version>

        </dependency>

        <!-- spring核心包 -->

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-core</artifactId>

            <version>${spring.version}</version>

        </dependency>

 

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-web</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-oxm</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-tx</artifactId>

            <version>${spring.version}</version>

        </dependency>

 

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-jdbc</artifactId>

            <version>${spring.version}</version>

        </dependency>

 

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-webmvc</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-test</artifactId>

            <version>${spring.version}</version>

        </dependency>

        <!-- 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>1.2.2</version>

        </dependency>

        <!-- 导入java ee jar 包 -->

        <dependency>

            <groupId>javax</groupId>

            <artifactId>javaee-api</artifactId>

            <version>7.0</version>

        </dependency>

        <!-- 导入Mysql数据库链接jar包 -->

        <dependency>

            <groupId>mysql</groupId>

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

            <version>5.1.30</version>

        </dependency>

        <!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->

        <dependency>

            <groupId>commons-dbcp</groupId>

            <artifactId>commons-dbcp</artifactId>

            <version>1.2.2</version>

        </dependency>

        <!-- JSTL标签类 -->

        <dependency>

            <groupId>jstl</groupId>

            <artifactId>jstl</artifactId>

            <version>1.2</version>

        </dependency>

        <!-- 日志文件管理包 -->

        <!-- log start -->

        <dependency>

            <groupId>log4j</groupId>

            <artifactId>log4j</artifactId>

            <version>${log4j.version}</version>

        </dependency>

 

 

        <!-- Redis客户端jedis依赖 -->

        <dependency>

            <groupId>redis.clients</groupId>

            <artifactId>jedis</artifactId>

            <version>2.7.0</version>

        </dependency>

 

        <!-- spring-data-redis依赖 -->

        <dependency>

            <groupId>org.springframework.data</groupId>

            <artifactId>spring-data-redis</artifactId>

            <version>1.5.0.RELEASE</version>

        </dependency>

 

 

        <!-- 格式化对象,方便输出日志 -->

        <dependency>

            <groupId>com.alibaba</groupId>

            <artifactId>fastjson</artifactId>

            <version>1.1.41</version>

        </dependency>

 

 

        <dependency>

            <groupId>org.slf4j</groupId>

            <artifactId>slf4j-api</artifactId>

            <version>${slf4j.version}</version>

        </dependency>

 

        <dependency>

            <groupId>org.slf4j</groupId>

            <artifactId>slf4j-log4j12</artifactId>

            <version>${slf4j.version}</version>

        </dependency>

        <!-- log end -->

        <!-- 映入JSON -->

        <dependency>

            <groupId>org.codehaus.jackson</groupId>

            <artifactId>jackson-mapper-asl</artifactId>

            <version>1.9.13</version>

        </dependency>

        <!-- 上传组件包 -->

        <dependency>

            <groupId>commons-fileupload</groupId>

            <artifactId>commons-fileupload</artifactId>

            <version>1.3.1</version>

        </dependency>

        <dependency>

            <groupId>commons-io</groupId>

            <artifactId>commons-io</artifactId>

            <version>2.4</version>

        </dependency>

        <dependency>

            <groupId>commons-codec</groupId>

            <artifactId>commons-codec</artifactId>

            <version>1.9</version>

        </dependency>

 

 

    </dependencies>

    <build>

        <finalName>ssmDemo</finalName>

        <plugins>

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-compiler-plugin</artifactId>

                <configuration>

                    <source>1.8</source>

                    <target>1.8</target>

                </configuration>

            </plugin>

        </plugins>

    </build>

</project>

 

配置文件:

spring-mvc.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

<?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:p="http://www.springframework.org/schema/p"

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

    xmlns:mvc="http://www.springframework.org/schema/mvc"

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

                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 

                        http://www.springframework.org/schema/context 

                        http://www.springframework.org/schema/context/spring-context-3.1.xsd 

                        http://www.springframework.org/schema/mvc 

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

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 -->

    <context:component-scan base-package="com.ssm" />

     

    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->

    <bean id="mappingJacksonHttpMessageConverter"

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

        <property name="supportedMediaTypes">

            <list>

                <value>text/html;charset=UTF-8</value>

            </list>

        </property>

    </bean>

    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->

    <bean

        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

        <property name="messageConverters">

            <list>

                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON转换器 -->

            </list>

        </property>

    </bean>

    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->

    <bean

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

        <!-- 这里的配置我的理解是自动给后面action的方法return的字符串加上前缀和后缀,变成一个 可用的url地址 -->

        <property name="prefix" value="/WEB-INF/jsp/" />

        <property name="suffix" value=".jsp" />

    </bean>

 

    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->

    <bean id="multipartResolver"

        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!-- 默认编码 -->

        <property name="defaultEncoding" value="utf-8" />

        <!-- 文件大小最大值 -->

        <property name="maxUploadSize" value="10485760000" />

        <!-- 内存中的最大值 -->

        <property name="maxInMemorySize" value="40960" />

    </bean>

 

</beans>

 

mybatis-config.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<?xml version="1.0" encoding="UTF-8" ?> 

<!DOCTYPE configuration 

  PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 

  "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

 

    <settings>

        <!-- 这个配置使全局的映射器启用或禁用缓存 -->

        <setting name="cacheEnabled" value="true" />

        <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->

        <setting name="multipleResultSetsEnabled" value="true" />

        <!-- 配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 -->

        <setting name="defaultExecutorType" value="REUSE" />

        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 -->

        <setting name="lazyLoadingEnabled" value="false" />

        <setting name="aggressiveLazyLoading" value="true" />

        <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间。 -->

        <setting name="defaultStatementTimeout" value="25000" />

    </settings>

    <mappers>

        <mapper resource="com/ssm/mapping/UserMapper.xml" />

    </mappers>

</configuration>

  

spring-mybatis.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

<?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-3.0.xsd

           http://www.springframework.org/schema/context 

           http://www.springframework.org/schema/context/spring-context-3.0.xsd

           http://www.springframework.org/schema/aop

           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

           http://www.springframework.org/schema/tx

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

 

    <!-- 引入配置文件 -->

    <bean id="propertyConfigurer"

        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

        <property name="location" value="classpath:jdbc.properties" />

    </bean>

 

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"

        destroy-method="close">

        <property name="driverClassName" value="${driver}" />

        <property name="url" value="${url}" />

        <property name="username" value="${username}" />

        <property name="password" value="${password}" />

        <!-- 初始化连接大小 -->

        <property name="initialSize" value="${initialSize}"></property>

        <!-- 连接池最大数量 -->

        <property name="maxActive" value="${maxActive}"></property>

        <!-- 连接池最大空闲 -->

        <property name="maxIdle" value="${maxIdle}"></property>

        <!-- 连接池最小空闲 -->

        <property name="minIdle" value="${minIdle}"></property>

        <!-- 获取连接最大等待时间 -->

        <property name="maxWait" value="${maxWait}"></property>

    </bean>

 

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="dataSource" />

        <!-- 自动扫描mapping.xml文件 -->

        <property name="configLocation" value="classpath:mybatis-config.xml"></property>

    </bean>

 

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <property name="basePackage" value="com.ssm.dao" />

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>

    </bean>

 

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->

    <bean id="transactionManager"

        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSource" />

    </bean>

 

</beans>

 

applicationContext.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

<?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-3.0.xsd

           http://www.springframework.org/schema/context 

           http://www.springframework.org/schema/context/spring-context-3.0.xsd

           http://www.springframework.org/schema/aop

           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd

           http://www.springframework.org/schema/tx

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

 

    <!--其实component-scan 就有了annotation-config的功能即把需要的类注册到了spring容器中 -->

    <context:component-scan base-package="com。ssm.service" />

    <!--配置事务注解 -->

    <tx:annotation-driven transaction-manager="transactionManager" />

 

    <!-- redis配置 -->

    <!-- redis连接池 -->

    <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">

        <property name="maxTotal" value="300"></property>

        <property name="maxIdle" value="200"></property>

        <property name="MaxWaitMillis" value="10000"></property>

        <property name="testOnBorrow" value="true"></property>

        <property name="testOnReturn" value="true"></property>

    </bean>

    <!-- redis连接工厂 -->

    <bean id="connectionFactory"

        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">

        <property name="hostName" value="127.0.0.1"></property>

        <property name="port" value="6379"></property>

        <property name="poolConfig" ref="jedisConfig"></property>

    </bean>

 

    <!-- redis操作模板,这里采用尽量面向对象的模板 -->

    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">

        <property name="connectionFactory" ref="connectionFactory" />

 

        <property name="keySerializer">

            <bean

                class="org.springframework.data.redis.serializer.StringRedisSerializer" />

        </property>

        <property name="valueSerializer">

            <bean

                class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />

        </property>

 

        <property name="hashKeySerializer">

            <bean

                class="org.springframework.data.redis.serializer.StringRedisSerializer" />

        </property>

        <property name="hashValueSerializer">

            <bean

                class="org.springframework.data.redis.serializer.StringRedisSerializer" />

        </property>

 

    </bean>

 

</beans>

  

jdbc.properties

1

2

3

4

5

6

7

8

9

10

11

12

13

14

driver=com.mysql.jdbc.Driver

url=jdbc\:mysql\://localhost\:3306/production_ssm

username=root

password=123456

#\u5B9A\u4E49\u521D\u59CB\u8FDE\u63A5\u6570 

initialSize=0 

#\u5B9A\u4E49\u6700\u5927\u8FDE\u63A5\u6570 

maxActive=20 

#\u5B9A\u4E49\u6700\u5927\u7A7A\u95F2 

maxIdle=20 

#\u5B9A\u4E49\u6700\u5C0F\u7A7A\u95F2 

minIdle=1 

#\u5B9A\u4E49\u6700\u957F\u7B49\u5F85\u65F6\u95F4 

maxWait=60000 

  

log4j.properties

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

log4j.rootLogger=DEBUG, stdout   

         

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

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

log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n   

     

#log4j.appender.R=org.apache.log4j.DailyRollingFileAppender   

#log4j.appender.R.File=../logs/service.log   

#log4j.appender.R.layout=org.apache.log4j.PatternLayout   

#log4j.appender.R.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n   

     

log4j.logger.com.ibatis = debug   

log4j.logger.com.ibatis.common.jdbc.SimpleDataSource = debug   

log4j.logger.com.ibatis.common.jdbc.ScriptRunner = debug   

log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate = debug   

log4j.logger.java.sql.Connection = debug   

log4j.logger.java.sql.Statement = debug   

log4j.logger.java.sql.PreparedStatement = debug   

log4j.logger.java.sql.ResultSet =debug  

  

web.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    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"

    version="3.0">

    <display-name>Archetype Created Web Application</display-name>

 

    <!-- Spring和mybatis的配置文件 -->

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>classpath:spring-mybatis.xml,classpath:applicationContext.xml</param-value>

    </context-param>

    <!-- 编码过滤器 -->

    <filter>

        <filter-name>encodingFilter</filter-name>

        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>

        <async-supported>true</async-supported>

        <init-param>

            <param-name>encoding</param-name>

            <param-value>UTF-8</param-value>

        </init-param>

    </filter>

    <filter-mapping>

        <filter-name>encodingFilter</filter-name>

        <url-pattern>/*</url-pattern>

    </filter-mapping>

 

    <context-param>

        <param-name>log4jConfigLocation</param-name>

        <param-value>classpath:log4j.properties</param-value>

    </context-param>

    <listener>

        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>

    </listener>

 

    <!-- Spring监听器 -->

    <listener>

        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

    </listener>

    <!-- 防止Spring内存溢出监听器 -->

    <listener>

        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>

    </listener>

 

    <!-- Spring MVC servlet -->

    <servlet>

        <servlet-name>SpringMVC</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

            <param-name>contextConfigLocation</param-name>

            <param-value>classpath:spring-mvc.xml</param-value>

        </init-param>

        <load-on-startup>1</load-on-startup>

        <async-supported>true</async-supported>

    </servlet>

    <servlet-mapping>

        <servlet-name>SpringMVC</servlet-name>

        <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->

        <url-pattern>/</url-pattern>

    </servlet-mapping>

    <welcome-file-list>

        <welcome-file>/index.jsp</welcome-file>

    </welcome-file-list>

 

</web-app>

  

以上是一些相关的配置项,接下来是真正的java代码:

UserController.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

package com.ssm.controller;

 

import javax.servlet.http.HttpServletRequest;

 

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

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

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

 

import com.ssm.pojo.User;

import com.ssm.service.UserService;

 

@Controller

@RequestMapping("/user")

public class UserController {

 

    @Autowired

    private UserService userService;

 

    @RequestMapping("/showUser")

    public String toIndex(HttpServletRequest request, Model model) {

        int userId = Integer.parseInt(request.getParameter("id"));

        User user = this.userService.selectByPrimaryKey(userId);

        model.addAttribute("user", user);

        return "showUser";

    }

}

  

UserService.java

1

2

3

4

5

6

7

package com.ssm.service;

 

import com.ssm.pojo.User;

 

public interface UserService {

    User selectByPrimaryKey(Integer id);

}

  

UserServiceImpl.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

package com.ssm.service.impl;

 

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

import org.springframework.stereotype.Service;

 

import com.ssm.dao.UserMapper;

import com.ssm.pojo.User;

import com.ssm.service.UserService;

 

@Service("userServiceImpl")

public class UserServiceImpl implements UserService {

 

    @Autowired

    private UserMapper userMapper;

 

    public User selectByPrimaryKey(Integer id) {

 

        return userMapper.selectByPrimaryKey(id);

    }

 

}

 

UserMapper.java

1

2

3

4

5

6

7

package com.ssm.dao;

 

import com.ssm.pojo.User;

 

public interface UserMapper {

    User selectByPrimaryKey(Integer id);

}

  

UserExample.java是通过mybaitis的插件自动生成的,就不写了,后面提供源码。

 

User.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

package com.ssm.pojo;

 

import java.io.Serializable;

 

/**

 * user 类

 *

 * @author fhliuzhihu

 *

 */

public class User implements Serializable {

 

    /**

     * 使用jedis 需要序列化接口

     */

    private static final long serialVersionUID = 1L;

 

    private Integer id;

 

    private String userName;

 

    private String password;

 

    private Integer age;

 

    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;

    }

 

    public Integer getAge() {

        return age;

    }

 

    public void setAge(Integer age) {

        this.age = age;

    }

 

    @Override

    public String toString() {

        return "User [id=" + id + ", username=" + userName + ", password=" + password + ",age=" + age + "]";

    }

}

  

RedisCache.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

package com.ssm.redis;

 

import java.util.concurrent.locks.ReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

 

import org.apache.ibatis.cache.Cache;

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

 

import redis.clients.jedis.Jedis;

import redis.clients.jedis.JedisPool;

import redis.clients.jedis.JedisPoolConfig;

 

public class RedisCache implements Cache {

 

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /**

     * Jedis客户端

     */

 

    @Autowired

    private Jedis redisClient = createClient();

 

    private String id;

 

    public RedisCache(final String id) {

        if (id == null) {

            throw new IllegalArgumentException("必须传入ID");

        }

        System.out.println("MybatisRedisCache:id=" + id);

        this.id = id;

    }

 

    @Override

    public void clear() {

        redisClient.flushDB();

    }

 

    @Override

    public String getId() {

        return this.id;

    }

 

    @Override

    public Object getObject(Object key) {

        byte[] ob = redisClient.get(SerializeUtil.serialize(key.toString()));

        if (ob == null) {

            return null;

        }

        Object value = SerializeUtil.unSerialize(ob);

        return value;

    }

 

    @Override

    public ReadWriteLock getReadWriteLock() {

        return readWriteLock;

    }

 

    @Override

    public int getSize() {

        return Integer.valueOf(redisClient.dbSize().toString());

    }

 

    @Override

    public void putObject(Object key, Object value) {

        redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));

    }

 

    @Override

    public Object removeObject(Object key) {

        return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);

    }

 

    protected static Jedis createClient() {

 

        try {

            @SuppressWarnings("resource")

            JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1"6379);

            return pool.getResource();

        catch (Exception e) {

            e.printStackTrace();

        }

        throw new RuntimeException("初始化连接池错误");

    }

 

}

  

SerializeUtil.java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

package com.ssm.redis;

 

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

 

public class SerializeUtil {

    /**

     *

     * 序列化

     */

    public static byte[] serialize(Object obj) {

 

        ObjectOutputStream oos = null;

        ByteArrayOutputStream baos = null;

 

        try {

            // 序列化

            baos = new ByteArrayOutputStream();

            oos = new ObjectOutputStream(baos);

 

            oos.writeObject(obj);

            byte[] byteArray = baos.toByteArray();

            return byteArray;

 

        catch (IOException e) {

            e.printStackTrace();

        }

        return null;

    }

 

    /**

     *

     * 反序列化

     *

     * @param bytes

     * @return

     */

    public static Object unSerialize(byte[] bytes) {

 

        ByteArrayInputStream bais = null;

 

        try {

            // 反序列化为对象

            bais = new ByteArrayInputStream(bytes);

            ObjectInputStream ois = new ObjectInputStream(bais);

            return ois.readObject();

 

        catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

}

  

最后,UserMapper.xml

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

<?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.ssm.dao.UserMapper">

    <cache type="com.ssm.redis.RedisCache" />

    <resultMap id="BaseResultMap" type="com.ssm.pojo.User">

        <id column="id" jdbcType="INTEGER" property="id" />

        <result column="user_name" jdbcType="VARCHAR" property="userName" />

        <result column="password" jdbcType="VARCHAR" property="password" />

        <result column="age" jdbcType="INTEGER" property="age" />

    </resultMap>

    <sql id="Example_Where_Clause">

        <where>

            <foreach collection="oredCriteria" item="criteria" separator="or">

                <if test="criteria.valid">

                    <trim prefix="(" prefixOverrides="and" suffix=")">

                        <foreach collection="criteria.criteria" item="criterion">

                            <choose>

                                <when test="criterion.noValue">

                                    and ${criterion.condition}

                                </when>

                                <when test="criterion.singleValue">

                                    and ${criterion.condition} #{criterion.value}

                                </when>

                                <when test="criterion.betweenValue">

                                    and ${criterion.condition} #{criterion.value}

                                    and

                                    #{criterion.secondValue}

                                </when>

                                <when test="criterion.listValue">

                                    and ${criterion.condition}

                                    <foreach close=")" collection="criterion.value" item="listItem"

                                        open="(" separator=",">

                                        #{listItem}

                                    </foreach>

                                </when>

                            </choose>

                        </foreach>

                    </trim>

                </if>

            </foreach>

        </where>

    </sql>

    <sql id="Update_By_Example_Where_Clause">

        <where>

            <foreach collection="example.oredCriteria" item="criteria"

                separator="or">

                <if test="criteria.valid">

                    <trim prefix="(" prefixOverrides="and" suffix=")">

                        <foreach collection="criteria.criteria" item="criterion">

                            <choose>

                                <when test="criterion.noValue">

                                    and ${criterion.condition}

                                </when>

                                <when test="criterion.singleValue">

                                    and ${criterion.condition} #{criterion.value}

                                </when>

                                <when test="criterion.betweenValue">

                                    and ${criterion.condition} #{criterion.value}

                                    and

                                    #{criterion.secondValue}

                                </when>

                                <when test="criterion.listValue">

                                    and ${criterion.condition}

                                    <foreach close=")" collection="criterion.value" item="listItem"

                                        open="(" separator=",">

                                        #{listItem}

                                    </foreach>

                                </when>

                            </choose>

                        </foreach>

                    </trim>

                </if>

            </foreach>

        </where>

    </sql>

    <sql id="Base_Column_List">

        id, user_name, password, age

    </sql>

    <select id="selectByExample" parameterType="com.ssm.dao.UserExample"

        resultMap="BaseResultMap">

        select

        <if test="distinct">

            distinct

        </if>

        <include refid="Base_Column_List" />

        from user_t

        <if test="_parameter != null">

            <include refid="Example_Where_Clause" />

        </if>

        <if test="orderByClause != null">

            order by ${orderByClause}

        </if>

    </select>

    <select id="selectByPrimaryKey" parameterType="java.lang.Integer"

        resultMap="BaseResultMap">

        select

        <include refid="Base_Column_List" />

        from user_t

        where id = #{id,jdbcType=INTEGER}

    </select>

    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">

        delete from user_t

        where id = #{id,jdbcType=INTEGER}

    </delete>

    <delete id="deleteByExample" parameterType="com.ssm.dao.UserExample">

        delete from user_t

        <if test="_parameter != null">

            <include refid="Example_Where_Clause" />

        </if>

    </delete>

    <insert id="insert" parameterType="com.ssm.pojo.User">

        insert into user_t (id,

        user_name, password,

        age)

        values (#{id,jdbcType=INTEGER},

        #{userName,jdbcType=VARCHAR},

        #{password,jdbcType=VARCHAR},

        #{age,jdbcType=INTEGER})

    </insert>

    <insert id="insertSelective" parameterType="com.ssm.pojo.User">

        insert into user_t

        <trim prefix="(" suffix=")" suffixOverrides=",">

            <if test="id != null">

                id,

            </if>

            <if test="userName != null">

                user_name,

            </if>

            <if test="password != null">

                password,

            </if>

            <if test="age != null">

                age,

            </if>

        </trim>

        <trim prefix="values (" suffix=")" suffixOverrides=",">

            <if test="id != null">

                #{id,jdbcType=INTEGER},

            </if>

            <if test="userName != null">

                #{userName,jdbcType=VARCHAR},

            </if>

            <if test="password != null">

                #{password,jdbcType=VARCHAR},

            </if>

            <if test="age != null">

                #{age,jdbcType=INTEGER},

            </if>

        </trim>

    </insert>

    <select id="countByExample" parameterType="com.ssm.dao.UserExample"

        resultType="java.lang.Integer">

        select count(*) from user_t

        <if test="_parameter != null">

            <include refid="Example_Where_Clause" />

        </if>

    </select>

    <update id="updateByExampleSelective" parameterType="map">

        update user_t

        <set>

            <if test="record.id != null">

                id = #{record.id,jdbcType=INTEGER},

            </if>

            <if test="record.userName != null">

                user_name = #{record.userName,jdbcType=VARCHAR},

            </if>

            <if test="record.password != null">

                password = #{record.password,jdbcType=VARCHAR},

            </if>

            <if test="record.age != null">

                age = #{record.age,jdbcType=INTEGER},

            </if>

        </set>

        <if test="_parameter != null">

            <include refid="Update_By_Example_Where_Clause" />

        </if>

    </update>

    <update id="updateByExample" parameterType="map">

        update user_t

        set id = #{record.id,jdbcType=INTEGER},

        user_name =

        #{record.userName,jdbcType=VARCHAR},

        password =

        #{record.password,jdbcType=VARCHAR},

        age =

        #{record.age,jdbcType=INTEGER}

        <if test="_parameter != null">

            <include refid="Update_By_Example_Where_Clause" />

        </if>

    </update>

    <update id="updateByPrimaryKeySelective" parameterType="com.ssm.pojo.User">

        update user_t

        <set>

            <if test="userName != null">

                user_name = #{userName,jdbcType=VARCHAR},

            </if>

            <if test="password != null">

                password = #{password,jdbcType=VARCHAR},

            </if>

            <if test="age != null">

                age = #{age,jdbcType=INTEGER},

            </if>

        </set>

        where id = #{id,jdbcType=INTEGER}

    </update>

    <update id="updateByPrimaryKey" parameterType="com.ssm.pojo.User">

        update user_t

        set

        user_name = #{userName,jdbcType=VARCHAR},

        password =

        #{password,jdbcType=VARCHAR},

        age = #{age,jdbcType=INTEGER}

        where id =

        #{id,jdbcType=INTEGER}

    </update>

</mapper>

  

其中,UserMapper.xml中,最重要的就是

1

<cache type="com.ssm.redis.RedisCache" />

 

这个是需要缓存哪个实体类,那么就在哪个的mapper.xml中添加上这一句!

测试:

启动本地的redis,然后启动项目,浏览器中输入:http://localhost:8080/ssmDemo/user/showUser?id=1    

后台日志:

 第一次,直接查询数据库数据。

  

 

通过RedisDesktopManager查询本地redis,发现数据已经存在了redis中:

 

 再次刷新页面,查看后台日志:

 

ok,ssm集成redis的步骤就是这些了,不过怎么说呢,还是有点儿问题,就是RedisCache获得Jedis的过程,我觉得应该是需要直接通过@Autowired获取,但是我这个就是通过createClient();这个方法获取的,所以有问题,回头看看怎么更改吧!

好吧,代码写的很渣,但是还是放上去,供大家参考一下,一起学习吧!

github下载地址:https://github.com/liuzhihu/ssmRedis

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值