【小编】杨海吉---六郎
【来源】Java资源社区
【主题】此篇文章主要实现,将数据库数据读取,并存储到redis中;
【工具】大家需要在本地安装redis客户端
【注】SSM架构的搭建大家可以参考网上的,这里我将一些重要的代码片段写出来,仅供参考!Spring整合redis
jar包地址:dependency>
groupId>redis.clientsgroupId>
artifactId>jedisartifactId>
version>2.7.3version>
dependency>
配置文件: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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd'>
context:component-scan base-package='com.ssm.service.impl' />
context:component-scan base-package='com.ssm.utils' />
bean
class='org.springframework.beans.factory.config.PropertyPlaceholderConfigurer'>
property name='locations'>
list>
value>classpath:jdbc.propertiesvalue>
value>classpath:redis.propertiesvalue>
list>
property>
bean>
bean id='dataSource' class='com.mchange.v2.c3p0.ComboPooledDataSource '
destroy-method='close'>
property name='driverClass' value='com.mysql.jdbc.Driver' />
property name='jdbcUrl'
value='jdbc:mysql://${jdbc.host}:${jdbc.port}/${jdbc.database}?useUnicode=true&characterEncoding=utf8' />
property name='user' value='${jdbc.username}' />
property name='password' value='${jdbc.password}' />
property name='acquireIncrement' value='1' />
property name='initialPoolSize' value='5' />
property name='maxPoolSize' value='20' />
property name='minPoolSize' value='5' />
property name='maxStatements' value='100' />
property name='testConnectionOnCheckout' value='true' />
bean>
bean id='sqlSessionFactory' class='org.mybatis.spring.SqlSessionFactoryBean'>
property name='dataSource' ref='dataSource' />
bean>
bean class='org.mybatis.spring.mapper.MapperScannerConfigurer'>
property name='basePackage' value='com.ssm.dao' />
bean>
tx:annotation-driven transaction-manager='transactionManager' />
bean id='transactionManager'
class='org.springframework.jdbc.datasource.DataSourceTransactionManager'>
property name='dataSource' ref='dataSource' />
bean>
bean id='poolConfig' class='redis.clients.jedis.JedisPoolConfig'>
property name='maxIdle' value='${redis.maxIdle}' />
property name='maxTotal' value='${redis.maxActive}' />
property name='maxWaitMillis' value='${redis.maxWait}' />
property name='testOnBorrow' value='${redis.testOnBorrow}' />
bean>
bean id='jedisConnectionFactory'
class='org.springframework.data.redis.connection.jedis.JedisConnectionFactory'>
property name='hostName' value='${redis.host}' />
property name='port' value='${redis.port}' />
property name='database' value='${redis.dbIndex}' />
property name='poolConfig' ref='poolConfig' />
bean>
bean id='redisTemplate' class='org.springframework.data.redis.core.RedisTemplate'>
property name='connectionFactory' ref='jedisConnectionFactory' />
bean>
bean id='redisCacheManager' class='org.springframework.data.redis.cache.RedisCacheManager'>
constructor-arg name='redisOperations' ref='redisTemplate' />
property name='defaultExpiration' value='${redis.expiration}' />
bean>
bean id='redisCacheConfig' class='com.ssm.utils.RedisCacheConfig'>
constructor-arg ref='jedisConnectionFactory' />
constructor-arg ref='redisTemplate' />
constructor-arg ref='redisCacheManager' />
bean>
beans>
测试代码:public static void main(String[] args){
//连接本地的 Redis 服务
Jedis jedis = new Jedis('localhost');
System.out.println('连接成功');
//查看服务是否运行
System.out.println('服务正在运行: '+jedis.ping());
//设置 redis 字符串数据Exception in thread 'main' redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect
jedis.get('redis');
// 获取存储的数据并输出
System.out.println('redis 存储的字符串为: '+ jedis.get('redis'));
}
如图表示连接成功:
redis在项目中应用
Controller实现:以Json形式返回,这里进行读取并存储,仅供参考@Controller
@RequestMapping('/uesrrdeis/')
public class UserController{
@Autowired
private UserService userService;
/**
*
* @Title: showUser
* @Description: 查询用户
* @param @param model
* @param @return 参数
* @return String 返回类型
* @throws
*/
@RequestMapping('showUser')
public void showUser(Model model,HttpServletRequest req,HttpServletResponse res)throws Exception{
System.out.println('----showUser----');
ListuserList = new ArrayList();
userList = userService.getAllUser();
Jedis jedis = new Jedis('localhost');
model.addAttribute('userList',userList);
JSONArray jsonArr = JSONArray.fromObject(userList);
//设置 redis 字符串数据
jedis.set('redis', userList.toString());
//获取存储的数据并输出
System.out.println('redis 存储的字符串为: '+ jedis.get('redis'));
res.setCharacterEncoding('utf-8');
PrintWriter writer = res.getWriter();
writer.write(jsonArr.toString());
writer.close();
//return 'showUser';
}
Service实现:/**
*
* @ClassName: UserServiceImpl
* @Description: 缓存机制说明:所有的查询结果都放进了缓存,也就是把MySQL查询的结果放到了redis中去,
* 然后第二次发起该条查询时就可以从redis中去读取查询的结果,从而不与MySQL交互,从而达到优化的效果,
* redis的查询速度之于MySQL的查询速度相当于 内存读写速度 /硬盘读写速度
* @Cacheable('a')注解的意义就是把该方法的查询结果放到redis中去,下一次再发起查询就去redis中去取,存在redis中的数据的key就是a;
* @CacheEvict(value={'a','b'},allEntries=true) 的意思就是执行该方法后要清除redis中key名称为a,b的数据;
* @author yang hai ji
* @date 2018年4月19日
*/
@Service('userService')
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Cacheable('getAllUser') //标注该方法查询的结果进入缓存,再次访问时直接读取缓存中的数据
@Override
public ListgetAllUser(){
return this.userMapper.selectAllUser();
}整体效果展示
1.页面展示:
2.redis展示:
3.控制台展示:
到这里就实现了简单的存储,当然大家可以通过Mybatis的二级缓存或者redis自身进行缓存处理,写的不好请多多指教,互相学习,有疑惑,可以联系小编,微信:372787553