RoleMapper接口:
package com.wbg.springRedis.dao;import com.wbg.springRedis.entity.Role;import org.springframework.stereotype.Repository;import java.util.List;@Repositorypublic interface RoleMapper { ListlistAll(); int add(Role role);}
xml映射:
insert into role(role_name,note) values(#{roleName},#{note})
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 ListlistRole() 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
>(){}); }*/ //如果存在 就返回 if (redisTemplate.hasKey(key)){ return om.readValue((String) redisTemplate.opsForValue().get(key), new TypeReference
>() { }); } List list = roleMapper.listAll(); //原生设置值 //jedis.set(key, om.writeValueAsString(list)); //设置 redisTemplate.opsForValue().set(key, om.writeValueAsString(list)); return list; }