zoukankan      html  css  js  c++  java
  • 使用Redis进行简单的数据缓存

    引入spring-data-redis包、jedis、connection-pool包

    applicationContext.xml的配置

        <!-- redis Connection -->
        <bean id="redisConnection" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="localhost"></property>
        <property name="port" value="6379"></property>
        </bean>
        <!-- redisTemplate -->
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="redisConnection"></property>
        </bean>

    做一个简单的测试

    @Test
        public void test1() {
            Jedis jd = new Jedis("localhost",6379);
            String ping = jd.ping();
            System.out.println(ping);
            Set<String> keys = jd.keys("*");
            for(String k:keys){
                System.out.println(k + ":"+ jd.type(k));
            }
            jd.close();
          
        }
        
        @Test
        public void test2(){
            Jedis j=new Jedis("localhost", 6379);
            System.out.println(j.ping());
            Set<String>  filed=  j.hkeys("dept");
            System.out.println(filed);
            for(String s:filed){
                System.out.println(j.hget("dept", s));
            }
            j.close();
        }

    自己写一个工具类将,进行序列化与反序列化,

    public class SerializableUtil {
    
        public static byte[] objectToBytes(Object obj) {// 将对象转换为byte数组
            ByteArrayOutputStream baos = null;
            ObjectOutputStream oos = null;
            try {
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(obj);// 将数据序列化后写入到baos中
                byte[] byte1 = baos.toByteArray();
                return byte1;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            } finally {
                try {
                    baos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    oos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
        }
    
        public static Object byteToObject(byte[] bytes) {
            ByteArrayInputStream bais = null;
            ObjectInputStream ois = null;
            try {
                bais = new ByteArrayInputStream(bytes);
                ois = new ObjectInputStream(bais);
                Object obj = ois.readObject();
                return obj;
    
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            } finally {
    
                try {
                    bais.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    ois.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }
    
        }
    View Code

    测试:

    @Test
        public void test4(){
            
            DeptBean bean=new DeptBean(124, "zhangsan1", "shanghai");
            Jedis j=new Jedis("localhost", 6379);
            j.set("dept".getBytes(), SerializableUtil.objectToBytes(bean));
            j.close();
        }
        
        @Test
        public void test5(){
            Jedis j=new Jedis("localhost", 6379);
            byte[] bean=j.get("dept".getBytes());//获取到的是byte数组
            //在将byte数组反序列化
            DeptBean byteToObject = (DeptBean) SerializableUtil.byteToObject(bean);
            System.out.println(byteToObject);
            j.close();
        }

    上面只是简单的使用自己写的一个工具类进行序列化与反序列化,实际开发中还是使用工具进行的,

    写一个控制器,对其进行单元测试

    @RunWith(SpringJUnit4ClassRunner.class)//这里的意思是进行一个spring环境的配置
    @ContextConfiguration(locations = "classpath:applicationContext.xml")//让其能不启动tomcat服务器的情况下进行测试
    public class TestRedis_Data {
    
        @Autowired//自动装载
        public RedisTemplate<Object, Object> tem;
    
        @Test
        public void test1() {
            // tem.setConnectionFactory(connectionFactory);
            // RedisTemplate
            DeptBean dept = new DeptBean(10, "傻强", "上海");
            tem.opsForValue().set("mydeptsingle", dept);//直接可以设置对象,将其进行序列化
            DeptBean object = (DeptBean) tem.opsForValue().get("mydeptsingle");// 底层已经序列化了
            System.out.println(object.getDeptno() + " " + object.getDname() + "  " + object.getLoc());
        }
    
    }

    然后在对自己有缓存需求的方法进行开启Redis缓存,

    //@Controller 
    @RestController //相当于@Controller 和 @ResponseBody 相结合的功能 
    public class DeptController {
    
        @Autowired //自动装载
        private DeptDao dao;
    
        //使用redis
        @Autowired
        private RedisTemplate<Object, Object> temp;
    
        @RequestMapping(value = "/dept/all", method = RequestMethod.GET) // @ResponseBody
        public List<DeptBean> selectAll() {
            List<DeptBean> Deptlist = (List<DeptBean>) temp.opsForValue().get("Deptlist");
            List<DeptBean> list = null;
            if (Deptlist.isEmpty()) {
                list = dao.findAll();
                temp.opsForValue().set("Deptlist", list);
                return list;
            }
            return Deptlist;
        }
    
        // 查询
        @RequestMapping(value = "/dept/get", method = RequestMethod.GET)
        public DeptBean selelctDeptById(@RequestParam("no") int id) {
            // 从Redis中取出来
            DeptBean bean = (DeptBean) temp.opsForValue().get("dept" + id);
            // 如果没有,从数据库中取出来并返回
            if (bean == null) {
                System.out.println("从数据库中取");
                DeptBean findbean = dao.findId(id);
                temp.opsForValue().set("dept" + id, findbean);
                return findbean;
            }
            System.out.println("从缓存中取的数据");
            return bean;
        }
    
        // 分页查询
        // 骑牛地址: http://localhost:8060/Spring_Mybatis02/dept/list?page=3&size=3
        @RequestMapping(value = "/dept/list", method = RequestMethod.GET)
        public PageBean pageSelect(
                @RequestParam(defaultValue = "1", required = false) int page,
                @RequestParam(defaultValue = "5", required = false) int size) {
            Page p = PageHelper.startPage(page, size);// 引入jar包中的jar文件,分页只对下一条查询代码有作用
            
            
            List<DeptBean> list = dao.findAll();
            System.out.println("当前页" + p.getPageNum() + "  总页数" + p.getPages() + "  总记录数" + p.getTotal());
            PageBean bean = new PageBean();
            bean.setList(list);
            bean.setPagesize(size);
            bean.setTotalpages(p.getPages());
            bean.setTotalRecords(p.getTotal());
            return bean;
        }
    
        // 删除
        @RequestMapping(value = "/dept/delete", method = RequestMethod.POST)
        public int deleteDeptById(int deptno) {
            //删除缓存
            temp.delete("dept" + deptno);
            //从数据库删除
            return dao.deleteDeptById(deptno);
        }
    }

     当然如果你需要在项目启动时候就加载到内存中,则可以这样,另写一个专门加载需要缓存的数据

    @Component
    public class InitLoadData {
        @Resource //装载dao层
        private DeptDao dao;
        @Resource
        private RedisTemplate<Object,Object> temp;  //装载Redis中的bean配置
        
        @PostConstruct//项目启动时候就会启动该方法 的注解
        public void inint(){
            System.out.println("查询数据库将数据加载到Redis中");
            DeptBean dept=dao.findId(10);
            temp.opsForValue().set("dept10", dept);
            
        }
    }
  • 相关阅读:
    VS中常用设置记录
    MSBUILD结合批处理编译
    Linq to XML 基本类
    在Winform和WPF中注册全局快捷键
    Unity 配置文件 基本设置
    C# 通用Clone
    三次样条插值特点与实现 (引用了一点别人代码,但做了改动!)
    修正短时自相关函数
    矩阵的基本运算
    去红眼不完善 MATLAB 代码
  • 原文地址:https://www.cnblogs.com/hx1098/p/9368806.html
Copyright © 2011-2022 走看看