使用Redis存取数据+数据库存取(spring+java)
Posted 邦☆杠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Redis存取数据+数据库存取(spring+java)相关的知识,希望对你有一定的参考价值。
RoleMapper接口:
package com.wbg.springRedis.dao; import com.wbg.springRedis.entity.Role; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface RoleMapper { List<Role> listAll(); int add(Role role); }
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.wbg.springRedis.dao.RoleMapper"> <insert id="add" parameterType="com.wbg.springRedis.entity.Role"> insert into role(role_name,note) values(#{roleName},#{note}) </insert> <select id="listAll" resultType="com.wbg.springRedis.entity.Role"> select * from role </select> </mapper>
Role类:
package com.wbg.springRedis.entity; import java.io.Serializable; public class Role { private int id; private String roleName; private String note; @Override public String toString() { return "Role{" + "id=" + id + ", roleName=‘" + roleName + ‘‘‘ + ", note=‘" + note + ‘‘‘ + ‘}‘; } public Role() { } public Role(String roleName, String note) { this.roleName = roleName; this.note = note; } public Role(int id, String roleName, String note) { this.id = id; this.roleName = roleName; this.note = note; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
xml文件:
//纯java @Bean public JedisConnectionFactory jedisConnectionFactory(){ JedisConnectionFactory jcf = new JedisConnectionFactory(); jcf.setHostName("localhost"); return jcf; } @Bean public RedisTemplate redisTemplate(){ RedisTemplate rt = new RedisTemplate(); rt.setConnectionFactory(jedisConnectionFactory()); rt.setKeySerializer(new StringRedisSerializer()); rt.setValueSerializer(new StringRedisSerializer()); return rt; }
@Autowired private RedisTemplate redisTemplate; @Autowired private RoleMapper roleMapper;
public List<Role> listRole() throws IOException { //使用jackJson序列化 ObjectMapper om = new ObjectMapper(); //键 String key = "listRole"; //原生 //Jedis jedis = new Jedis(); /* if (jedis.exists(key)){ return om.readValue(jedis.get(key), new TypeReference<List<Role>>(){}); }*/ //如果存在 就返回 if (redisTemplate.hasKey(key)){ return om.readValue((String) redisTemplate.opsForValue().get(key), new TypeReference<List<Role>>() { }); } List<Role> list = roleMapper.listAll(); //原生设置值 //jedis.set(key, om.writeValueAsString(list)); //设置 redisTemplate.opsForValue().set(key, om.writeValueAsString(list)); return list; }
以上是关于使用Redis存取数据+数据库存取(spring+java)的主要内容,如果未能解决你的问题,请参考以下文章